@leitwerk-dev/server 0.1.6 → 0.1.8

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 (143) hide show
  1. package/dist/app.d.ts.map +1 -1
  2. package/dist/app.js +31 -40
  3. package/dist/app.js.map +1 -1
  4. package/dist/auth/auth-client.d.ts +25 -0
  5. package/dist/auth/auth-client.d.ts.map +1 -0
  6. package/dist/auth/auth-client.js +19 -0
  7. package/dist/auth/auth-client.js.map +1 -0
  8. package/dist/auth/auth-config.d.ts +8 -2
  9. package/dist/auth/auth-config.d.ts.map +1 -1
  10. package/dist/auth/auth-config.js +17 -7
  11. package/dist/auth/auth-config.js.map +1 -1
  12. package/dist/auth/auth-service.d.ts +2 -0
  13. package/dist/auth/auth-service.d.ts.map +1 -1
  14. package/dist/auth/auth-service.js +9 -5
  15. package/dist/auth/auth-service.js.map +1 -1
  16. package/dist/auth/auth-test-helpers.js +2 -2
  17. package/dist/auth/auth-test-helpers.js.map +1 -1
  18. package/dist/auth/github-oauth-client.d.ts +20 -0
  19. package/dist/auth/github-oauth-client.d.ts.map +1 -0
  20. package/dist/auth/github-oauth-client.js +79 -0
  21. package/dist/auth/github-oauth-client.js.map +1 -0
  22. package/dist/auth/oidc-client.d.ts +4 -4
  23. package/dist/{chunk-G4PCN46L.js → chunk-ES5RBLAT.js} +47 -99
  24. package/dist/chunk-ES5RBLAT.js.map +1 -0
  25. package/dist/{chunk-KVHAK5UR.js → chunk-UC3OOEQ3.js} +527 -410
  26. package/dist/chunk-UC3OOEQ3.js.map +1 -0
  27. package/dist/config/config-loader.d.ts.map +1 -1
  28. package/dist/config/config-loader.js +21 -89
  29. package/dist/config/config-loader.js.map +1 -1
  30. package/dist/config/config-types.d.ts +18 -3
  31. package/dist/config/config-types.d.ts.map +1 -1
  32. package/dist/domain-logic/outcome-tools.d.ts +2 -2
  33. package/dist/domain-logic/outcome-tools.d.ts.map +1 -1
  34. package/dist/domain-logic/outcome-tools.js +1 -1
  35. package/dist/domain-logic/outcome-tools.js.map +1 -1
  36. package/dist/index.d.ts +1 -1
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +1 -1
  39. package/dist/index.js.map +1 -1
  40. package/dist/integration-tool-registry.d.ts +23 -0
  41. package/dist/integration-tool-registry.d.ts.map +1 -0
  42. package/dist/integration-tool-registry.js +140 -0
  43. package/dist/integration-tool-registry.js.map +1 -0
  44. package/dist/model-providers/builtin-server-adapter.d.ts.map +1 -1
  45. package/dist/model-providers/builtin-server-adapter.js +10 -2
  46. package/dist/model-providers/builtin-server-adapter.js.map +1 -1
  47. package/dist/process-ui-snapshot-presenter.d.ts.map +1 -1
  48. package/dist/process-ui-snapshot-presenter.js +0 -2
  49. package/dist/process-ui-snapshot-presenter.js.map +1 -1
  50. package/dist/process-watcher-registry.d.ts +3 -31
  51. package/dist/process-watcher-registry.d.ts.map +1 -1
  52. package/dist/process-watcher-registry.js +96 -97
  53. package/dist/process-watcher-registry.js.map +1 -1
  54. package/dist/routes/watchers.d.ts.map +1 -1
  55. package/dist/routes/watchers.js +14 -50
  56. package/dist/routes/watchers.js.map +1 -1
  57. package/dist/semantic-state-json.d.ts +1 -2
  58. package/dist/semantic-state-json.d.ts.map +1 -1
  59. package/dist/semantic-state-json.js +1 -2
  60. package/dist/semantic-state-json.js.map +1 -1
  61. package/dist/supervisor/ipc-handler.d.ts +4 -1
  62. package/dist/supervisor/ipc-handler.d.ts.map +1 -1
  63. package/dist/supervisor/ipc-handler.js +18 -0
  64. package/dist/supervisor/ipc-handler.js.map +1 -1
  65. package/dist/supervisor/worker-start-payload-builder.d.ts +5 -4
  66. package/dist/supervisor/worker-start-payload-builder.d.ts.map +1 -1
  67. package/dist/supervisor/worker-start-payload-builder.js +9 -0
  68. package/dist/supervisor/worker-start-payload-builder.js.map +1 -1
  69. package/dist/supervisor/worker-supervisor.d.ts +4 -5
  70. package/dist/supervisor/worker-supervisor.d.ts.map +1 -1
  71. package/dist/supervisor/worker-supervisor.js +6 -0
  72. package/dist/supervisor/worker-supervisor.js.map +1 -1
  73. package/dist/test-helpers/fake-worker-supervisor.d.ts.map +1 -1
  74. package/dist/test-helpers/fake-worker-supervisor.js +1 -0
  75. package/dist/test-helpers/fake-worker-supervisor.js.map +1 -1
  76. package/dist/test-helpers/ipc-handler-harness.d.ts +1 -0
  77. package/dist/test-helpers/ipc-handler-harness.d.ts.map +1 -1
  78. package/dist/test-helpers/ipc-handler-harness.js +4 -3
  79. package/dist/test-helpers/ipc-handler-harness.js.map +1 -1
  80. package/dist/test-helpers/process-fixtures.js +3 -3
  81. package/dist/test-helpers/process-fixtures.js.map +1 -1
  82. package/dist/{writes-irEq9SlA.d.ts → writes-CVXLCYce.d.ts} +61 -13
  83. package/package.json +10 -10
  84. package/src/app.ts +37 -44
  85. package/src/auth/auth-client.ts +40 -0
  86. package/src/auth/auth-config.ts +34 -9
  87. package/src/auth/auth-service.ts +11 -5
  88. package/src/auth/auth-test-helpers.ts +2 -2
  89. package/src/auth/github-oauth-client.ts +111 -0
  90. package/src/auth/oidc-client.ts +5 -5
  91. package/src/config/config-loader.ts +42 -103
  92. package/src/config/config-types.ts +21 -3
  93. package/src/domain-logic/outcome-tools.ts +3 -3
  94. package/src/index.ts +1 -4
  95. package/src/integration-tool-registry.ts +186 -0
  96. package/src/model-providers/builtin-server-adapter.ts +10 -2
  97. package/src/process-ui-snapshot-presenter.ts +0 -2
  98. package/src/process-watcher-registry.ts +124 -167
  99. package/src/routes/watchers.ts +14 -50
  100. package/src/semantic-state-json.ts +0 -2
  101. package/src/supervisor/ipc-handler.ts +35 -0
  102. package/src/supervisor/worker-start-payload-builder.ts +21 -1
  103. package/src/supervisor/worker-supervisor.ts +14 -4
  104. package/src/test-helpers/fake-worker-supervisor.ts +1 -0
  105. package/src/test-helpers/ipc-handler-harness.ts +7 -3
  106. package/src/test-helpers/process-fixtures.ts +3 -3
  107. package/dist/chunk-G4PCN46L.js.map +0 -1
  108. package/dist/chunk-KVHAK5UR.js.map +0 -1
  109. package/dist/domain-logic/idempotency.d.ts +0 -3
  110. package/dist/domain-logic/idempotency.d.ts.map +0 -1
  111. package/dist/domain-logic/idempotency.js +0 -3
  112. package/dist/domain-logic/idempotency.js.map +0 -1
  113. package/dist/domain-logic/index.d.ts +0 -7
  114. package/dist/domain-logic/index.d.ts.map +0 -1
  115. package/dist/domain-logic/index.js +0 -6
  116. package/dist/domain-logic/index.js.map +0 -1
  117. package/dist/domain-logic/input-sequencer.d.ts +0 -16
  118. package/dist/domain-logic/input-sequencer.d.ts.map +0 -1
  119. package/dist/domain-logic/input-sequencer.js +0 -2
  120. package/dist/domain-logic/input-sequencer.js.map +0 -1
  121. package/dist/domain-logic/string-normalize.d.ts +0 -2
  122. package/dist/domain-logic/string-normalize.d.ts.map +0 -1
  123. package/dist/domain-logic/string-normalize.js +0 -2
  124. package/dist/domain-logic/string-normalize.js.map +0 -1
  125. package/dist/filesystem-process-watchers.d.ts +0 -22
  126. package/dist/filesystem-process-watchers.d.ts.map +0 -1
  127. package/dist/filesystem-process-watchers.js +0 -79
  128. package/dist/filesystem-process-watchers.js.map +0 -1
  129. package/dist/test-helpers/in-process-worker.d.ts +0 -2
  130. package/dist/test-helpers/in-process-worker.d.ts.map +0 -1
  131. package/dist/test-helpers/in-process-worker.js +0 -2
  132. package/dist/test-helpers/in-process-worker.js.map +0 -1
  133. package/dist/test-helpers/leaf-outcome-fixtures.d.ts +0 -37
  134. package/dist/test-helpers/leaf-outcome-fixtures.d.ts.map +0 -1
  135. package/dist/test-helpers/leaf-outcome-fixtures.js +0 -81
  136. package/dist/test-helpers/leaf-outcome-fixtures.js.map +0 -1
  137. package/src/domain-logic/idempotency.ts +0 -3
  138. package/src/domain-logic/index.ts +0 -31
  139. package/src/domain-logic/input-sequencer.ts +0 -18
  140. package/src/domain-logic/string-normalize.ts +0 -1
  141. package/src/filesystem-process-watchers.ts +0 -147
  142. package/src/test-helpers/in-process-worker.ts +0 -2
  143. package/src/test-helpers/leaf-outcome-fixtures.ts +0 -140
@@ -71,7 +71,7 @@ import {
71
71
  snapshotLiveTurnProjection,
72
72
  truncateTextAtWordBoundary,
73
73
  validateConfig
74
- } from "./chunk-G4PCN46L.js";
74
+ } from "./chunk-ES5RBLAT.js";
75
75
 
76
76
  // src/extension-ui/catalog.ts
77
77
  import { readFile, stat } from "fs/promises";
@@ -1395,6 +1395,11 @@ function requireApiKey(secrets) {
1395
1395
  }
1396
1396
  return value;
1397
1397
  }
1398
+ function configuredBaseUrl(config) {
1399
+ if (!config || typeof config !== "object" || Array.isArray(config)) return void 0;
1400
+ const value = config.baseUrl;
1401
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
1402
+ }
1398
1403
  function createBuiltinPiServerAdapter(builtinProviderId) {
1399
1404
  return definePiServerAdapter({
1400
1405
  async generateText(input) {
@@ -1403,10 +1408,12 @@ function createBuiltinPiServerAdapter(builtinProviderId) {
1403
1408
  `Built-in adapter '${builtinProviderId}' cannot serve provider '${input.providerId}'`
1404
1409
  );
1405
1410
  }
1406
- const model = getModel(builtinProviderId, input.modelId);
1407
- if (!model) {
1411
+ const canonicalModel = getModel(builtinProviderId, input.modelId);
1412
+ if (!canonicalModel) {
1408
1413
  throw new Error(`Built-in Pi model '${builtinProviderId}/${input.modelId}' is unavailable`);
1409
1414
  }
1415
+ const baseUrl = configuredBaseUrl(input.config);
1416
+ const model = baseUrl ? { ...canonicalModel, baseUrl } : canonicalModel;
1410
1417
  const reasoning = resolveThinkingLevel(input.thinkingLevel);
1411
1418
  const message = await completeSimple(
1412
1419
  model,
@@ -2743,17 +2750,13 @@ function buildTurnFailedWrites(input) {
2743
2750
  }
2744
2751
 
2745
2752
  // src/domain-logic/outcome-tools.ts
2753
+ import { normalizeStringArray, trimString } from "@leitwerk-dev/domain";
2746
2754
  import {
2747
2755
  isAutomaticTurnDefinition,
2748
2756
  isLlmTurnDefinition,
2749
2757
  isServerAutomaticTurnDefinition
2750
2758
  } from "@leitwerk-dev/process-sdk";
2751
2759
  import * as v2 from "valibot";
2752
-
2753
- // src/domain-logic/string-normalize.ts
2754
- import { normalizeStringArray, trimString, trimToNull } from "@leitwerk-dev/domain";
2755
-
2756
- // src/domain-logic/outcome-tools.ts
2757
2760
  function validationFailure(code, message) {
2758
2761
  return { ok: false, code, message };
2759
2762
  }
@@ -3107,7 +3110,6 @@ function resolveProductTurnResultMarkdown(input) {
3107
3110
  // src/semantic-state-json.ts
3108
3111
  import {
3109
3112
  parseProcessStateJsonStrict,
3110
- parseSemanticEntryRefsFromStateJsonStrict,
3111
3113
  parseSemanticEntryRefsStrict
3112
3114
  } from "@leitwerk-dev/domain";
3113
3115
  var parseProcessStateJsonRecord = parseProcessStateJsonStrict;
@@ -7362,7 +7364,7 @@ import {
7362
7364
  createAgentSessionServices,
7363
7365
  SessionManager
7364
7366
  } from "@earendil-works/pi-coding-agent";
7365
- import { trimToNull as trimToNull2 } from "@leitwerk-dev/domain";
7367
+ import { trimToNull } from "@leitwerk-dev/domain";
7366
7368
  import { expandPiAgentDir } from "@leitwerk-dev/process-sdk/pi-config";
7367
7369
  import { createDurableWsFrame as createDurableWsFrame4, parseFutureLaunchPayloadJson } from "@leitwerk-dev/protocol";
7368
7370
  import { parseDurationMs } from "@leitwerk-dev/watcher-utils";
@@ -7388,7 +7390,7 @@ function getFutureExecutionTitleJobTarget(job) {
7388
7390
  };
7389
7391
  }
7390
7392
  function normalizeProcessTitle(value) {
7391
- const trimmed = trimToNull2(value);
7393
+ const trimmed = trimToNull(value);
7392
7394
  if (!trimmed) {
7393
7395
  return null;
7394
7396
  }
@@ -7400,7 +7402,7 @@ function normalizeProcessTitle(value) {
7400
7402
  return normalizeProcessTitleInput(withoutQuotes);
7401
7403
  }
7402
7404
  function normalizeSourceValue(value) {
7403
- const trimmed = trimToNull2(value);
7405
+ const trimmed = trimToNull(value);
7404
7406
  if (!trimmed) {
7405
7407
  return null;
7406
7408
  }
@@ -7413,7 +7415,7 @@ function buildProcessTitleSourceFields(launchPlan) {
7413
7415
  if (normalized.length >= MAX_SOURCE_FIELDS) {
7414
7416
  break;
7415
7417
  }
7416
- const label = trimToNull2(field.label) ?? `Field ${normalized.length + 1}`;
7418
+ const label = trimToNull(field.label) ?? `Field ${normalized.length + 1}`;
7417
7419
  const value = normalizeSourceValue(field.value);
7418
7420
  if (!value) {
7419
7421
  continue;
@@ -7593,7 +7595,7 @@ var DefaultProcessTitleGenerator = class {
7593
7595
  this.runtime = runtime;
7594
7596
  this.extensionHost = extensionHost;
7595
7597
  this.futureExecutionTitleApplier = futureExecutionTitleApplier;
7596
- this.configuredProfileId = trimToNull2(config.pi.process_title_generation.model_profile);
7598
+ this.configuredProfileId = trimToNull(config.pi.process_title_generation.model_profile);
7597
7599
  this.retryPolicy = buildProcessTitleRetryPolicy(config);
7598
7600
  this.expandedAgentDir = expandPiAgentDir(config.pi.agent_dir);
7599
7601
  this.pollIntervalMs = Math.max(1, Math.trunc(runtime.pollIntervalMs));
@@ -8066,42 +8068,41 @@ function buildLaunchPlan(watcher, launchConfig, commitMessages) {
8066
8068
  launcherId: `${watcher.processId}.${watcher.definition.id}`,
8067
8069
  metadataAdditions: {
8068
8070
  processWatcherId: watcher.definition.id,
8069
- processWatcherType: watcher.definition.type,
8071
+ processWatcherSourceId: watcher.definition.source.id,
8070
8072
  processWatcherConfigPath: watcher.configPath
8071
8073
  },
8072
8074
  errorSubject: `Process watcher '${watcher.definition.id}'`,
8073
8075
  commitMessages
8074
8076
  });
8075
8077
  }
8076
- function buildWatcherLaunchModelConfig(launch) {
8077
- const turnConfigs = Object.fromEntries(
8078
- Object.entries(launch?.turn_configs ?? {}).map(([turnId, turnConfig]) => [
8079
- turnId,
8080
- { modelProfileId: turnConfig.model_profile ?? null }
8081
- ])
8082
- );
8083
- return {
8084
- defaultModelProfileId: launch?.default_model_profile ?? null,
8085
- turnConfigs
8086
- };
8087
- }
8088
- function buildRegistrationView(watcher) {
8089
- return {
8090
- processId: watcher.processId,
8091
- processDisplayName: watcher.processDisplayName,
8092
- watcherId: watcher.definition.id,
8093
- watcherLabel: watcher.definition.label,
8094
- watcherDescription: watcher.definition.description,
8095
- type: watcher.definition.type,
8096
- enabled: watcher.config.enabled,
8097
- pollInterval: watcher.config.poll_interval,
8098
- configPath: watcher.configPath,
8099
- config: structuredClone(watcher.config),
8100
- launchModelConfig: structuredClone(watcher.launchModelConfig)
8101
- };
8102
- }
8103
- function watcherKey(processId, watcherId) {
8104
- return `${processId}:${watcherId}`;
8078
+ function parseConfiguredWatcher(input) {
8079
+ try {
8080
+ const parsed = input.definition.source.parseConfig(input.rawConfig);
8081
+ if (typeof parsed.enabled !== "boolean") {
8082
+ throw new Error("parseConfig() must return a boolean enabled value");
8083
+ }
8084
+ const presentation = input.definition.source.presentConfig(parsed.config);
8085
+ if (presentation.targetSummary.trim() === "") {
8086
+ throw new Error("presentConfig() must return a non-empty targetSummary");
8087
+ }
8088
+ return {
8089
+ processId: input.processId,
8090
+ processDisplayName: input.processDisplayName,
8091
+ processDef: input.processDef,
8092
+ definition: input.definition,
8093
+ config: parsed.config,
8094
+ enabled: parsed.enabled,
8095
+ presentation,
8096
+ configPath: input.configPath,
8097
+ launchModelConfig: parsed.launchModelConfig ?? {
8098
+ defaultModelProfileId: null,
8099
+ turnConfigs: {}
8100
+ }
8101
+ };
8102
+ } catch (error) {
8103
+ const message = error instanceof Error ? error.message : String(error);
8104
+ throw new Error(`${input.configPath}: ${message}`, { cause: error });
8105
+ }
8105
8106
  }
8106
8107
  function validateWatcherLaunchModelConfig(processId, modelConfig, policy) {
8107
8108
  const errors = [];
@@ -8114,102 +8115,92 @@ function validateWatcherLaunchModelConfig(processId, modelConfig, policy) {
8114
8115
  }
8115
8116
  return errors;
8116
8117
  }
8117
- function validateConfiguredProcessWatchersAgainstCatalog(input) {
8118
+ function collectConfiguredProcessWatchers(input) {
8119
+ const watchers = [];
8118
8120
  const errors = [];
8119
8121
  for (const [processId, processConfig] of Object.entries(input.config.process_configs ?? {})) {
8120
- if (!input.catalog.processes.has(processId)) {
8121
- continue;
8122
- }
8123
8122
  const processDef = input.catalog.processes.get(processId);
8124
- if (!processDef) {
8125
- continue;
8126
- }
8127
- const built = collectProcessWatchers(processDef);
8128
- const configuredWatchers = processConfig.watchers ?? {};
8129
- for (const [watcherId, watcherConfig] of Object.entries(configuredWatchers)) {
8130
- const watcherDef = built.get(watcherId);
8131
- if (!watcherDef) {
8132
- errors.push(
8133
- `Unknown watcher '${watcherId}' at process_configs.${processId}.watchers.${watcherId}`
8134
- );
8123
+ if (!processDef) continue;
8124
+ const definitions = collectProcessWatchers(processDef);
8125
+ for (const [watcherId, rawConfig] of Object.entries(processConfig.watchers ?? {})) {
8126
+ const configPath = `process_configs.${processId}.watchers.${watcherId}`;
8127
+ const definition = definitions.get(watcherId);
8128
+ if (!definition) {
8129
+ errors.push(`Unknown watcher '${watcherId}' at ${configPath}`);
8135
8130
  continue;
8136
8131
  }
8137
- if (watcherDef.type !== watcherConfig.type) {
8138
- errors.push(
8139
- `Watcher '${watcherId}' at process_configs.${processId}.watchers.${watcherId} configured type '${watcherConfig.type}' does not match declared watcher type '${watcherDef.type}'`
8140
- );
8141
- }
8142
- if (input.processModelPolicy) {
8143
- errors.push(
8144
- ...validateWatcherLaunchModelConfig(
8145
- processId,
8146
- buildWatcherLaunchModelConfig(watcherConfig.launch),
8147
- input.processModelPolicy
8148
- )
8149
- );
8132
+ try {
8133
+ const watcher = parseConfiguredWatcher({
8134
+ processId,
8135
+ processDisplayName: processDef.displayName,
8136
+ processDef,
8137
+ definition,
8138
+ rawConfig,
8139
+ configPath
8140
+ });
8141
+ watchers.push(watcher);
8142
+ if (input.processModelPolicy) {
8143
+ errors.push(
8144
+ ...validateWatcherLaunchModelConfig(
8145
+ processId,
8146
+ watcher.launchModelConfig,
8147
+ input.processModelPolicy
8148
+ )
8149
+ );
8150
+ }
8151
+ } catch (error) {
8152
+ errors.push(error instanceof Error ? error.message : String(error));
8150
8153
  }
8151
8154
  }
8152
8155
  }
8153
- return errors;
8156
+ return { watchers, errors };
8154
8157
  }
8155
8158
  function buildProcessWatcherRegistry(catalog, config, options = {}) {
8156
- const watchers = /* @__PURE__ */ new Map();
8157
- for (const [processId, processDef] of catalog.processes) {
8158
- const built = collectProcessWatchers(processDef);
8159
- const processWatchers = config.process_configs?.[processId]?.watchers ?? {};
8160
- for (const [watcherId, watcherConfig] of Object.entries(processWatchers)) {
8161
- const watcherDef = built.get(watcherId);
8162
- if (!watcherDef || watcherDef.type !== watcherConfig.type) {
8163
- continue;
8164
- }
8165
- watchers.set(watcherKey(processId, watcherId), {
8166
- processId,
8167
- processDisplayName: processDef.displayName,
8168
- processDef,
8169
- definition: watcherDef,
8170
- config: watcherConfig,
8171
- configPath: `process_configs.${processId}.watchers.${watcherId}`,
8172
- launchModelConfig: buildWatcherLaunchModelConfig(watcherConfig.launch)
8173
- });
8174
- }
8159
+ const { watchers, errors } = collectConfiguredProcessWatchers({
8160
+ catalog,
8161
+ config,
8162
+ processModelPolicy: options.processModelPolicy
8163
+ });
8164
+ if (errors.length > 0) {
8165
+ throw new Error(`Invalid process watcher config:
8166
+ ${errors.join("\n")}`);
8175
8167
  }
8176
8168
  const getDefaultModelProfilesForProcess = (processId) => options.getModelProfilesForProcess?.(processId) ?? options.modelProfiles ?? [];
8177
8169
  const createWatcherContext = (processId, ctx = {}) => ({
8178
8170
  ...ctx,
8179
8171
  modelProfiles: ctx.modelProfiles ?? getDefaultModelProfilesForProcess(processId)
8180
8172
  });
8181
- const sortedWatchers = [...watchers.values()].sort((a, b) => {
8173
+ const registrations = watchers.sort((a, b) => {
8182
8174
  const processCompare = a.processDisplayName.localeCompare(b.processDisplayName);
8183
- if (processCompare !== 0) {
8184
- return processCompare;
8185
- }
8186
- return a.definition.label.localeCompare(b.definition.label);
8187
- });
8188
- return {
8189
- listAll() {
8190
- return sortedWatchers.map(buildRegistrationView);
8191
- },
8192
- listByType(type) {
8193
- return sortedWatchers.filter((watcher) => watcher.definition.type === type).map(buildRegistrationView);
8194
- },
8195
- async resolveLaunch(processId, watcherId, payload, ctx = {}) {
8196
- const watcher = watchers.get(watcherKey(processId, watcherId));
8197
- if (!watcher) {
8198
- return null;
8199
- }
8200
- const watcherContext = createWatcherContext(processId, ctx);
8201
- if (watcher.definition.matches) {
8202
- const matches = await watcher.definition.matches(payload, watcherContext);
8203
- if (!matches) {
8175
+ return processCompare !== 0 ? processCompare : a.definition.label.localeCompare(b.definition.label);
8176
+ }).map((watcher) => ({
8177
+ source: watcher.definition.source,
8178
+ view: {
8179
+ processId: watcher.processId,
8180
+ processDisplayName: watcher.processDisplayName,
8181
+ watcherId: watcher.definition.id,
8182
+ watcherLabel: watcher.definition.label,
8183
+ watcherDescription: watcher.definition.description,
8184
+ sourceId: watcher.definition.source.id,
8185
+ sourceLabel: watcher.definition.source.label,
8186
+ enabled: watcher.enabled,
8187
+ configPath: watcher.configPath,
8188
+ config: structuredClone(watcher.config),
8189
+ presentation: structuredClone(watcher.presentation),
8190
+ launchModelConfig: structuredClone(watcher.launchModelConfig),
8191
+ async resolveLaunch(event, ctx = {}) {
8192
+ const watcherContext = createWatcherContext(watcher.processId, ctx);
8193
+ if (watcher.definition.matches && !await watcher.definition.matches(event, watcherContext)) {
8204
8194
  return null;
8205
8195
  }
8196
+ const launchConfig = await watcher.definition.resolveLaunchConfig(event, watcherContext);
8197
+ return buildLaunchPlan(watcher, launchConfig, config.commit_messages);
8206
8198
  }
8207
- const launchConfig = await watcher.definition.resolveLaunchConfig(payload, watcherContext);
8208
- return {
8209
- watcher: buildRegistrationView(watcher),
8210
- launchPlan: buildLaunchPlan(watcher, launchConfig, config.commit_messages)
8211
- };
8212
8199
  }
8200
+ }));
8201
+ return {
8202
+ listAll: () => registrations.map(({ view }) => view),
8203
+ listBySource: (source) => registrations.filter((watcher) => watcher.source === source).map(({ view }) => view)
8213
8204
  };
8214
8205
  }
8215
8206
 
@@ -8359,56 +8350,20 @@ function summarizeLaunchModelConfig(modelConfig) {
8359
8350
  }
8360
8351
  function buildWatcherSummary(watcher) {
8361
8352
  const launchModel = summarizeLaunchModelConfig(watcher.launchModelConfig);
8362
- switch (watcher.config.type) {
8363
- case "jira":
8364
- return {
8365
- processId: watcher.processId,
8366
- processDisplayName: watcher.processDisplayName,
8367
- watcherId: watcher.watcherId,
8368
- label: watcher.watcherLabel,
8369
- description: watcher.watcherDescription,
8370
- type: "jira",
8371
- enabled: watcher.enabled,
8372
- pollInterval: watcher.pollInterval,
8373
- configPath: watcher.configPath,
8374
- launchModel,
8375
- targetSummary: `Jira project ${watcher.config.project} \xB7 trigger ${watcher.config.labels.trigger}`,
8376
- project: watcher.config.project,
8377
- labels: watcher.config.labels,
8378
- targetBranchLabelPrefix: watcher.config.target_branch_label_prefix
8379
- };
8380
- case "gitlab_mr":
8381
- return {
8382
- processId: watcher.processId,
8383
- processDisplayName: watcher.processDisplayName,
8384
- watcherId: watcher.watcherId,
8385
- label: watcher.watcherLabel,
8386
- description: watcher.watcherDescription,
8387
- type: "gitlab_mr",
8388
- enabled: watcher.enabled,
8389
- pollInterval: watcher.pollInterval,
8390
- configPath: watcher.configPath,
8391
- launchModel,
8392
- targetSummary: `GitLab group ${watcher.config.group} \xB7 trigger ${watcher.config.labels.trigger}`,
8393
- group: watcher.config.group,
8394
- labels: watcher.config.labels
8395
- };
8396
- case "filesystem":
8397
- return {
8398
- processId: watcher.processId,
8399
- processDisplayName: watcher.processDisplayName,
8400
- watcherId: watcher.watcherId,
8401
- label: watcher.watcherLabel,
8402
- description: watcher.watcherDescription,
8403
- type: "filesystem",
8404
- enabled: watcher.enabled,
8405
- pollInterval: watcher.pollInterval,
8406
- configPath: watcher.configPath,
8407
- launchModel,
8408
- targetSummary: `File ${watcher.config.file_path}`,
8409
- filePath: watcher.config.file_path
8410
- };
8411
- }
8353
+ return {
8354
+ processId: watcher.processId,
8355
+ processDisplayName: watcher.processDisplayName,
8356
+ watcherId: watcher.watcherId,
8357
+ label: watcher.watcherLabel,
8358
+ description: watcher.watcherDescription,
8359
+ sourceId: watcher.sourceId,
8360
+ sourceLabel: watcher.sourceLabel,
8361
+ enabled: watcher.enabled,
8362
+ configPath: watcher.configPath,
8363
+ launchModel,
8364
+ targetSummary: watcher.presentation.targetSummary,
8365
+ details: [...watcher.presentation.details ?? []]
8366
+ };
8412
8367
  }
8413
8368
  function registerWatcherRoutes(app, deps) {
8414
8369
  app.get("/api/watchers", async () => {
@@ -8797,6 +8752,22 @@ function createIpcHandler(deps, callbacks) {
8797
8752
  { instanceId, workerId, observation, reason }
8798
8753
  );
8799
8754
  switch (msg.type) {
8755
+ case "worker.integration_tool_cancel": {
8756
+ deps.handleIntegrationToolCancel?.(instanceId, msg.payload);
8757
+ break;
8758
+ }
8759
+ case "worker.integration_tool_request": {
8760
+ if (!deps.handleIntegrationToolRequest) break;
8761
+ void deps.handleIntegrationToolRequest(instanceId, msg.payload).then((payload) => callbacks.onIntegrationToolResult?.(instanceId, workerId, payload)).catch(
8762
+ () => callbacks.onIntegrationToolResult?.(instanceId, workerId, {
8763
+ turnRecordId: msg.payload.turnRecordId,
8764
+ toolCallId: msg.payload.toolCallId,
8765
+ ok: false,
8766
+ error: "Integration tool execution failed"
8767
+ })
8768
+ );
8769
+ break;
8770
+ }
8800
8771
  case "worker.credential_update": {
8801
8772
  const result = deps.updateCredential?.(msg.payload) ?? {
8802
8773
  accepted: false,
@@ -9672,6 +9643,15 @@ function createWorkerStartPayloadBuilder(deps) {
9672
9643
  projects: deps.projects.listByInstance(process2.id)
9673
9644
  }) ?? [];
9674
9645
  const bootstrap = resolveBootstrap(start, deps);
9646
+ const selectedTurn = deps.processActionRegistry.getTurnDefinition(
9647
+ process2.processId,
9648
+ start.turnId
9649
+ );
9650
+ const integrationToolNames = selectedTurn?.kind === "llm" ? selectedTurn.integrationTools ?? [] : [];
9651
+ const integrationTools = integrationToolNames.length > 0 ? deps.integrationTools?.declarations(integrationToolNames) : void 0;
9652
+ if (integrationToolNames.length > 0 && !integrationTools) {
9653
+ throw new Error(`Integration tools are unavailable for turn '${start.turnId}'`);
9654
+ }
9675
9655
  const payloadBase = {
9676
9656
  ...contextSnapshot,
9677
9657
  workerLeaseId: lease.id,
@@ -9685,7 +9665,8 @@ function createWorkerStartPayloadBuilder(deps) {
9685
9665
  resume: treePaths.resume,
9686
9666
  workerRuntimeSettings: buildWorkerRuntimeSettingsSnapshot(deps.config),
9687
9667
  ...treePaths.resume ? { resumeLeafEntryId } : {},
9688
- ...repositoryCredentials.length > 0 ? { repositoryCredentials } : {}
9668
+ ...repositoryCredentials.length > 0 ? { repositoryCredentials } : {},
9669
+ ...integrationTools && integrationTools.length > 0 ? { integrationTools } : {}
9689
9670
  };
9690
9671
  const payload = bootstrap.kind === "llm" ? {
9691
9672
  ...payloadBase,
@@ -10559,6 +10540,12 @@ function createWorkerSupervisor(deps) {
10559
10540
  questionResponse(instanceId, workerId, payload) {
10560
10541
  sendToCurrentWorker(instanceId, workerId, { type: "worker.question_response", payload });
10561
10542
  },
10543
+ integrationToolResult(instanceId, workerId, payload) {
10544
+ sendToCurrentWorker(instanceId, workerId, {
10545
+ type: "worker.integration_tool_result",
10546
+ payload
10547
+ });
10548
+ },
10562
10549
  credentialUpdateResult(instanceId, workerId, payload) {
10563
10550
  sendToCurrentWorker(instanceId, workerId, {
10564
10551
  type: "worker.credential_update_accepted",
@@ -10615,63 +10602,86 @@ import {
10615
10602
  } from "@leitwerk-dev/worker-runners";
10616
10603
  import Fastify from "fastify";
10617
10604
 
10618
- // src/auth/auth-config.ts
10619
- import { parseDurationMs as parseDurationMs4 } from "@leitwerk-dev/watcher-utils";
10620
- var DEFAULT_SESSION_COOKIE_NAME = "leitwerk_session";
10621
- var DEFAULT_SESSION_TTL = "7d";
10622
- var DEFAULT_LOGIN_FLOW_TTL_MS = 10 * 60 * 1e3;
10623
- function resolveAuthConfig(config) {
10624
- const auth = config.auth;
10625
- const serverBaseUrl = new URL(config.server.base_url);
10626
- const providers = (auth?.providers ?? []).map((provider) => ({
10627
- ...provider,
10628
- redirect_uri: provider.redirect_uri ?? new URL("/auth/callback", serverBaseUrl).toString(),
10629
- scopes: provider.scopes ?? ["openid", "profile", "email"],
10630
- identity_claim: provider.identity_claim ?? "preferred_username"
10631
- }));
10632
- const sessionCookieName = auth?.session?.cookie_name ?? DEFAULT_SESSION_COOKIE_NAME;
10605
+ // src/auth/github-oauth-client.ts
10606
+ import { randomBytes as randomBytes2 } from "crypto";
10607
+ var GITHUB_AUTHORIZE_URL = "https://github.com/login/oauth/authorize";
10608
+ var GITHUB_TOKEN_URL = "https://github.com/login/oauth/access_token";
10609
+ var GITHUB_API_URL = "https://api.github.com";
10610
+ var GITHUB_API_VERSION = "2022-11-28";
10611
+ function opaqueValue() {
10612
+ return randomBytes2(32).toString("base64url");
10613
+ }
10614
+ function githubHeaders(accessToken) {
10633
10615
  return {
10634
- enabled: auth?.enabled === true && providers.length > 0,
10635
- sessionCookieName,
10636
- loginFlowCookieName: `${sessionCookieName}_login`,
10637
- sessionTtlMs: parseDurationMs4(
10638
- auth?.session?.ttl ?? DEFAULT_SESSION_TTL,
10639
- 7 * 24 * 60 * 60 * 1e3,
10640
- {
10641
- allowHours: true
10642
- }
10643
- ),
10644
- loginFlowTtlMs: DEFAULT_LOGIN_FLOW_TTL_MS,
10645
- secureCookies: serverBaseUrl.protocol === "https:",
10646
- appBaseOrigin: serverBaseUrl.origin,
10647
- providers,
10648
- allowlist: new Set(auth?.allowlist ?? [])
10616
+ Accept: "application/vnd.github+json",
10617
+ "X-GitHub-Api-Version": GITHUB_API_VERSION,
10618
+ "User-Agent": "leitwerk-server",
10619
+ ...accessToken ? { Authorization: `Bearer ${accessToken}` } : {}
10649
10620
  };
10650
10621
  }
10651
- function isActorAllowedByConfig(actor, auth) {
10652
- if (!auth.enabled) {
10653
- return true;
10654
- }
10655
- if (actor.kind !== "user" || actor.provider === null) {
10656
- return false;
10657
- }
10658
- if (!auth.providers.some((provider) => provider.id === actor.provider)) {
10659
- return false;
10622
+ async function jsonObject(response, errorMessage3) {
10623
+ if (!response.ok) throw new Error(errorMessage3);
10624
+ const value = await response.json();
10625
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
10626
+ throw new Error(errorMessage3);
10660
10627
  }
10661
- const prefix = `${actor.provider}:`;
10662
- return actor.id.startsWith(prefix) && auth.allowlist.has(actor.id.slice(prefix.length));
10663
- }
10664
-
10665
- // src/auth/auth-tokens.ts
10666
- import { createHash as createHash3, randomBytes as randomBytes2 } from "crypto";
10667
- function generateOpaqueToken(byteLength = 32) {
10668
- return randomBytes2(byteLength).toString("base64url");
10669
- }
10670
- function hashOpaqueToken(token) {
10671
- return createHash3("sha256").update(token, "utf8").digest("base64url");
10628
+ return value;
10672
10629
  }
10673
- function isoFromNow(ms, now2 = /* @__PURE__ */ new Date()) {
10674
- return new Date(now2.getTime() + ms).toISOString();
10630
+ function createGithubOauthClient(fetchImpl = fetch) {
10631
+ return {
10632
+ async createAuthorizationRequest(provider) {
10633
+ const state = opaqueValue();
10634
+ const redirectUrl = new URL(GITHUB_AUTHORIZE_URL);
10635
+ redirectUrl.searchParams.set("client_id", provider.client_id);
10636
+ redirectUrl.searchParams.set("redirect_uri", provider.redirect_uri);
10637
+ redirectUrl.searchParams.set("scope", provider.scopes.join(" "));
10638
+ redirectUrl.searchParams.set("state", state);
10639
+ return {
10640
+ provider,
10641
+ state,
10642
+ // The persisted login-flow schema requires a verifier. GitHub OAuth Apps
10643
+ // authenticate this confidential client with its secret instead of PKCE.
10644
+ pkceVerifier: opaqueValue(),
10645
+ redirectUrl: redirectUrl.toString()
10646
+ };
10647
+ },
10648
+ async exchangeCallback({ provider, callbackUrl }) {
10649
+ const code = callbackUrl.searchParams.get("code");
10650
+ if (!code) throw new Error("GitHub OAuth callback did not include a code");
10651
+ const tokenResponse = await fetchImpl(GITHUB_TOKEN_URL, {
10652
+ method: "POST",
10653
+ headers: { ...githubHeaders(), "Content-Type": "application/x-www-form-urlencoded" },
10654
+ body: new URLSearchParams({
10655
+ client_id: provider.client_id,
10656
+ client_secret: provider.client_secret,
10657
+ code,
10658
+ redirect_uri: provider.redirect_uri
10659
+ }).toString()
10660
+ });
10661
+ const token = await jsonObject(tokenResponse, "GitHub OAuth token exchange failed");
10662
+ const accessToken = typeof token.access_token === "string" ? token.access_token : "";
10663
+ if (!accessToken) throw new Error("GitHub OAuth token exchange failed");
10664
+ const userResponse = await fetchImpl(`${GITHUB_API_URL}/user`, {
10665
+ headers: githubHeaders(accessToken)
10666
+ });
10667
+ const user = await jsonObject(userResponse, "GitHub user lookup failed");
10668
+ const login = typeof user.login === "string" ? user.login.trim().toLowerCase() : "";
10669
+ if (!login) throw new Error("GitHub user lookup failed");
10670
+ const organization = encodeURIComponent(provider.organization);
10671
+ const membershipResponse = await fetchImpl(
10672
+ `${GITHUB_API_URL}/user/memberships/orgs/${organization}`,
10673
+ { headers: githubHeaders(accessToken) }
10674
+ );
10675
+ const membership = await jsonObject(
10676
+ membershipResponse,
10677
+ "GitHub organization membership is not active"
10678
+ );
10679
+ if (membership.state !== "active") {
10680
+ throw new Error("GitHub organization membership is not active");
10681
+ }
10682
+ return { claims: { ...user, login } };
10683
+ }
10684
+ };
10675
10685
  }
10676
10686
 
10677
10687
  // src/auth/oidc-client.ts
@@ -10752,6 +10762,88 @@ function createOpenIdClient() {
10752
10762
  };
10753
10763
  }
10754
10764
 
10765
+ // src/auth/auth-client.ts
10766
+ function createAuthClient(input) {
10767
+ const oidc = input?.oidc ?? createOpenIdClient();
10768
+ const github = input?.github ?? createGithubOauthClient();
10769
+ return {
10770
+ createAuthorizationRequest(provider) {
10771
+ return provider.kind === "oidc" ? oidc.createAuthorizationRequest(provider) : github.createAuthorizationRequest(provider);
10772
+ },
10773
+ exchangeCallback(request) {
10774
+ return request.provider.kind === "oidc" ? oidc.exchangeCallback({ ...request, provider: request.provider }) : github.exchangeCallback({ ...request, provider: request.provider });
10775
+ }
10776
+ };
10777
+ }
10778
+
10779
+ // src/auth/auth-config.ts
10780
+ import { parseDurationMs as parseDurationMs4 } from "@leitwerk-dev/watcher-utils";
10781
+ var DEFAULT_SESSION_COOKIE_NAME = "leitwerk_session";
10782
+ var DEFAULT_SESSION_TTL = "7d";
10783
+ var DEFAULT_LOGIN_FLOW_TTL_MS = 10 * 60 * 1e3;
10784
+ function resolveAuthConfig(config) {
10785
+ const auth = config.auth;
10786
+ const serverBaseUrl = new URL(config.server.base_url);
10787
+ const providers = (auth?.providers ?? []).map(
10788
+ (provider) => provider.kind === "oidc" ? {
10789
+ ...provider,
10790
+ redirect_uri: provider.redirect_uri ?? new URL("/auth/callback", serverBaseUrl).toString(),
10791
+ scopes: provider.scopes ?? ["openid", "profile", "email"],
10792
+ identity_claim: provider.identity_claim ?? "preferred_username"
10793
+ } : {
10794
+ ...provider,
10795
+ redirect_uri: provider.redirect_uri ?? new URL("/auth/callback", serverBaseUrl).toString(),
10796
+ scopes: ["read:org"],
10797
+ identity_claim: "login"
10798
+ }
10799
+ );
10800
+ const sessionCookieName = auth?.session?.cookie_name ?? DEFAULT_SESSION_COOKIE_NAME;
10801
+ return {
10802
+ enabled: auth?.enabled === true && providers.length > 0,
10803
+ sessionCookieName,
10804
+ loginFlowCookieName: `${sessionCookieName}_login`,
10805
+ sessionTtlMs: parseDurationMs4(
10806
+ auth?.session?.ttl ?? DEFAULT_SESSION_TTL,
10807
+ 7 * 24 * 60 * 60 * 1e3,
10808
+ {
10809
+ allowHours: true
10810
+ }
10811
+ ),
10812
+ loginFlowTtlMs: DEFAULT_LOGIN_FLOW_TTL_MS,
10813
+ secureCookies: serverBaseUrl.protocol === "https:",
10814
+ appBaseOrigin: serverBaseUrl.origin,
10815
+ providers,
10816
+ allowlist: new Set(auth?.allowlist ?? [])
10817
+ };
10818
+ }
10819
+ function isActorAllowedByConfig(actor, auth) {
10820
+ if (!auth.enabled) {
10821
+ return true;
10822
+ }
10823
+ if (actor.kind !== "user" || actor.provider === null) {
10824
+ return false;
10825
+ }
10826
+ if (!auth.providers.some((provider2) => provider2.id === actor.provider)) {
10827
+ return false;
10828
+ }
10829
+ const prefix = `${actor.provider}:`;
10830
+ if (!actor.id.startsWith(prefix)) return false;
10831
+ const provider = auth.providers.find((candidate) => candidate.id === actor.provider);
10832
+ return provider?.kind === "oauth2" || auth.allowlist.has(actor.id.slice(prefix.length));
10833
+ }
10834
+
10835
+ // src/auth/auth-tokens.ts
10836
+ import { createHash as createHash3, randomBytes as randomBytes3 } from "crypto";
10837
+ function generateOpaqueToken(byteLength = 32) {
10838
+ return randomBytes3(byteLength).toString("base64url");
10839
+ }
10840
+ function hashOpaqueToken(token) {
10841
+ return createHash3("sha256").update(token, "utf8").digest("base64url");
10842
+ }
10843
+ function isoFromNow(ms, now2 = /* @__PURE__ */ new Date()) {
10844
+ return new Date(now2.getTime() + ms).toISOString();
10845
+ }
10846
+
10755
10847
  // src/auth/auth-service.ts
10756
10848
  function pickDisplayName(claims, identity) {
10757
10849
  for (const key of ["name", "preferred_username", "email"]) {
@@ -10786,7 +10878,9 @@ function consumeValidFlow(repos, cookieValue) {
10786
10878
  }
10787
10879
  function createAuthService(input) {
10788
10880
  const auth = resolveAuthConfig(input.config);
10789
- const oidcClient = input.oidcClient ?? createOpenIdClient();
10881
+ const authClient = input.authClient ?? createAuthClient({
10882
+ oidc: input.oidcClient ?? createOpenIdClient()
10883
+ });
10790
10884
  const sweepExpiredAuthState = () => ({
10791
10885
  sessions: input.repos.authSessions.deleteExpired(),
10792
10886
  loginFlows: input.repos.authLoginFlows.deleteExpired()
@@ -10800,7 +10894,7 @@ function createAuthService(input) {
10800
10894
  throw new Error("Authentication is not enabled");
10801
10895
  }
10802
10896
  const provider = auth.providers[0];
10803
- const login = await oidcClient.createAuthorizationRequest(provider);
10897
+ const login = await authClient.createAuthorizationRequest(provider);
10804
10898
  const cookieValue = generateOpaqueToken();
10805
10899
  const expiresAt = isoFromNow(auth.loginFlowTtlMs);
10806
10900
  input.repos.authLoginFlows.create({
@@ -10826,9 +10920,9 @@ function createAuthService(input) {
10826
10920
  throw new Error("Login provider is no longer configured");
10827
10921
  }
10828
10922
  if (callbackUrl.searchParams.get("state") !== flow.state) {
10829
- throw new Error("Invalid OIDC state");
10923
+ throw new Error("Invalid authentication state");
10830
10924
  }
10831
- const exchanged = await oidcClient.exchangeCallback({
10925
+ const exchanged = await authClient.exchangeCallback({
10832
10926
  provider,
10833
10927
  callbackUrl,
10834
10928
  state: flow.state,
@@ -10836,7 +10930,7 @@ function createAuthService(input) {
10836
10930
  });
10837
10931
  const actor = actorFromOidcClaims({ provider, claims: exchanged.claims });
10838
10932
  if (!actor) {
10839
- throw new Error(`OIDC identity claim ${provider.identity_claim} was not present`);
10933
+ throw new Error(`Authentication identity claim ${provider.identity_claim} was not present`);
10840
10934
  }
10841
10935
  if (!isActorAllowedByConfig(actor, auth)) {
10842
10936
  throw new Error("Authenticated user is not allowlisted");
@@ -11941,13 +12035,41 @@ function createExternalSourceService(deps) {
11941
12035
  };
11942
12036
  }
11943
12037
 
11944
- // src/filesystem-process-watchers.ts
12038
+ // src/future-execution/lifecycle.ts
12039
+ import {
12040
+ normalizeLaunchModelConfigInput,
12041
+ SYSTEM_ACTOR as SYSTEM_ACTOR4
12042
+ } from "@leitwerk-dev/domain";
11945
12043
  import {
11946
- consumeTriggerFile,
11947
- createPollLoop,
11948
- emptyPollResult,
11949
- readTriggerFile
11950
- } from "@leitwerk-dev/watcher-utils";
12044
+ parseFutureActionPayloadJson as parseFutureActionPayloadJson3,
12045
+ parseFutureLaunchPayloadJson as parseFutureLaunchPayloadJson4,
12046
+ serializeFutureActionPayload,
12047
+ serializeFutureLaunchPayload,
12048
+ validateScheduleRequestInput
12049
+ } from "@leitwerk-dev/protocol";
12050
+
12051
+ // src/domain-logic/cron.ts
12052
+ import { CronExpressionParser } from "cron-parser";
12053
+ var CRON_FIELD_COUNT = 5;
12054
+ function splitCronFields(expression) {
12055
+ return expression.trim().split(/\s+/).filter((field) => field.length > 0);
12056
+ }
12057
+ function nextCronOccurrenceUtc(expression, after = /* @__PURE__ */ new Date()) {
12058
+ const fields = splitCronFields(expression);
12059
+ if (fields.length !== CRON_FIELD_COUNT) {
12060
+ throw new Error("Cron expression must have exactly 5 fields: minute hour day month weekday");
12061
+ }
12062
+ const next = CronExpressionParser.parse(expression, {
12063
+ currentDate: after,
12064
+ tz: "UTC",
12065
+ strict: false
12066
+ }).next();
12067
+ const nextIso = next.toISOString();
12068
+ if (!nextIso) {
12069
+ throw new Error("Couldn't compute the next cron occurrence");
12070
+ }
12071
+ return nextIso;
12072
+ }
11951
12073
 
11952
12074
  // src/process-launch-executor.ts
11953
12075
  function mapLaunchStartFailure(result) {
@@ -12248,139 +12370,6 @@ async function createProcessFromLaunchPlanWithDisposition(deps, launchPlan, opts
12248
12370
  }
12249
12371
  }
12250
12372
 
12251
- // src/filesystem-process-watchers.ts
12252
- function createFilesystemProcessWatchersService(args) {
12253
- const watchers = args.processWatchers.listByType(
12254
- "filesystem"
12255
- );
12256
- const loops = watchers.map(
12257
- (watcher) => createPollLoop({
12258
- pollInterval: () => watcher.pollInterval,
12259
- isEnabled: () => watcher.enabled,
12260
- defaultIntervalMs: 1e3,
12261
- async pollOnce() {
12262
- const result = emptyPollResult();
12263
- if (watcher.config.type !== "filesystem") {
12264
- return result;
12265
- }
12266
- const file = await readTriggerFile(watcher.config.file_path);
12267
- if (!file.exists) {
12268
- return result;
12269
- }
12270
- const content = file.content.trim();
12271
- if (content.length === 0) {
12272
- return result;
12273
- }
12274
- const resolved = await args.processWatchers.resolveLaunch(
12275
- watcher.processId,
12276
- watcher.watcherId,
12277
- { filePath: watcher.config.file_path, content }
12278
- );
12279
- if (!resolved) {
12280
- result.skipped.push(`${watcher.processId}:${watcher.watcherId}`);
12281
- return result;
12282
- }
12283
- const prepared = await args.launchPlans.prepare(resolved.launchPlan, {
12284
- modelConfig: watcher.launchModelConfig,
12285
- invalidModelConfig: "omit"
12286
- });
12287
- if (!prepared.ok) {
12288
- result.errors.push(
12289
- ...prepared.errors.map(
12290
- (error) => `${watcher.processId}:${watcher.watcherId}:${error.code}`
12291
- )
12292
- );
12293
- args.logger?.warn(
12294
- {
12295
- processId: watcher.processId,
12296
- watcherId: watcher.watcherId,
12297
- filePath: watcher.config.file_path,
12298
- errors: prepared.errors
12299
- },
12300
- "Filesystem process watcher launch plan preparation failed"
12301
- );
12302
- return result;
12303
- }
12304
- const created = await createProcessFromLaunchPlan(
12305
- args.launchExecutorDeps,
12306
- prepared.launchPlan
12307
- );
12308
- const durableProcess = created.ok ? created.process : created.stage === "post_commit" ? created.process : null;
12309
- if (durableProcess) {
12310
- await consumeTriggerFile(watcher.config.file_path);
12311
- result.created.push(durableProcess.id);
12312
- }
12313
- if (!created.ok) {
12314
- result.errors.push(
12315
- `${watcher.processId}:${watcher.watcherId}:${created.status}:${String(created.body.error ?? "launch_failed")}`
12316
- );
12317
- args.logger?.warn(
12318
- {
12319
- processId: watcher.processId,
12320
- watcherId: watcher.watcherId,
12321
- filePath: watcher.config.file_path,
12322
- status: created.status,
12323
- body: created.body,
12324
- durableProcessId: durableProcess?.id ?? null
12325
- },
12326
- "Filesystem process watcher launch failed"
12327
- );
12328
- return result;
12329
- }
12330
- return result;
12331
- }
12332
- })
12333
- );
12334
- return {
12335
- start() {
12336
- for (const loop of loops) {
12337
- loop.start();
12338
- }
12339
- },
12340
- stop() {
12341
- for (const loop of loops) {
12342
- loop.stop();
12343
- }
12344
- }
12345
- };
12346
- }
12347
-
12348
- // src/future-execution/lifecycle.ts
12349
- import {
12350
- normalizeLaunchModelConfigInput,
12351
- SYSTEM_ACTOR as SYSTEM_ACTOR4
12352
- } from "@leitwerk-dev/domain";
12353
- import {
12354
- parseFutureActionPayloadJson as parseFutureActionPayloadJson3,
12355
- parseFutureLaunchPayloadJson as parseFutureLaunchPayloadJson4,
12356
- serializeFutureActionPayload,
12357
- serializeFutureLaunchPayload,
12358
- validateScheduleRequestInput
12359
- } from "@leitwerk-dev/protocol";
12360
-
12361
- // src/domain-logic/cron.ts
12362
- import { CronExpressionParser } from "cron-parser";
12363
- var CRON_FIELD_COUNT = 5;
12364
- function splitCronFields(expression) {
12365
- return expression.trim().split(/\s+/).filter((field) => field.length > 0);
12366
- }
12367
- function nextCronOccurrenceUtc(expression, after = /* @__PURE__ */ new Date()) {
12368
- const fields = splitCronFields(expression);
12369
- if (fields.length !== CRON_FIELD_COUNT) {
12370
- throw new Error("Cron expression must have exactly 5 fields: minute hour day month weekday");
12371
- }
12372
- const next = CronExpressionParser.parse(expression, {
12373
- currentDate: after,
12374
- tz: "UTC",
12375
- strict: false
12376
- }).next();
12377
- const nextIso = next.toISOString();
12378
- if (!nextIso) {
12379
- throw new Error("Couldn't compute the next cron occurrence");
12380
- }
12381
- return nextIso;
12382
- }
12383
-
12384
12373
  // src/process-launch-plan-model-config.ts
12385
12374
  function clearLaunchPlanModelConfig(launchPlan) {
12386
12375
  return {
@@ -13830,6 +13819,143 @@ function startFutureExecutionScheduler(lifecycle, options = {}) {
13830
13819
  };
13831
13820
  }
13832
13821
 
13822
+ // src/integration-tool-registry.ts
13823
+ import {
13824
+ RESERVED_INTEGRATION_TOOL_NAMES
13825
+ } from "@leitwerk-dev/process-sdk";
13826
+ var TOOL_NAME = /^[a-z][a-z0-9_]{0,63}$/;
13827
+ var RESERVED_TOOL_NAMES = new Set(RESERVED_INTEGRATION_TOOL_NAMES);
13828
+ function parseToolArgs(value) {
13829
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
13830
+ throw new Error("Integration tool arguments must be an object");
13831
+ }
13832
+ return value;
13833
+ }
13834
+ var IntegrationToolRegistry = class {
13835
+ tools = /* @__PURE__ */ new Map();
13836
+ executions = /* @__PURE__ */ new Map();
13837
+ register(definition) {
13838
+ const name = definition.name;
13839
+ if (!TOOL_NAME.test(name)) {
13840
+ throw new Error(`Integration tool '${definition.name}' must match ${TOOL_NAME}`);
13841
+ }
13842
+ if (RESERVED_TOOL_NAMES.has(name)) {
13843
+ throw new Error(`Integration tool '${name}' uses a reserved tool name`);
13844
+ }
13845
+ if (definition.description.trim() === "") {
13846
+ throw new Error(`Integration tool '${name}' requires a description`);
13847
+ }
13848
+ if (this.tools.has(name)) throw new Error(`Duplicate integration tool '${name}'`);
13849
+ this.tools.set(name, definition);
13850
+ }
13851
+ declarations(names) {
13852
+ return names.map((name) => {
13853
+ const definition = this.tools.get(name);
13854
+ if (!definition) throw new Error(`Unknown integration tool '${name}'`);
13855
+ return {
13856
+ name: definition.name,
13857
+ description: definition.description,
13858
+ parameters: definition.parameters
13859
+ };
13860
+ });
13861
+ }
13862
+ execute(name, args, ctx) {
13863
+ const definition = this.tools.get(name);
13864
+ if (!definition) return Promise.reject(new Error(`Unknown integration tool '${name}'`));
13865
+ const existing = this.executions.get(ctx.idempotencyKey);
13866
+ if (existing) return existing.promise;
13867
+ const controller = new AbortController();
13868
+ const promise = Promise.resolve().then(() => {
13869
+ if (controller.signal.aborted) {
13870
+ throw new Error("Integration tool execution cancelled");
13871
+ }
13872
+ return definition.execute(
13873
+ { ...ctx, signal: controller.signal },
13874
+ definition.parse?.(args) ?? parseToolArgs(args)
13875
+ );
13876
+ }).finally(() => this.executions.delete(ctx.idempotencyKey));
13877
+ this.executions.set(ctx.idempotencyKey, { controller, promise });
13878
+ return promise;
13879
+ }
13880
+ cancel(idempotencyKey) {
13881
+ const execution = this.executions.get(idempotencyKey);
13882
+ if (!execution) return false;
13883
+ execution.controller.abort();
13884
+ return true;
13885
+ }
13886
+ };
13887
+ function integrationToolIdempotencyKey(input) {
13888
+ return `${input.instanceId}:${input.turnRecordId}:${input.toolCallId}:${input.toolName}`;
13889
+ }
13890
+ function createIntegrationToolRequestService(input) {
13891
+ return {
13892
+ cancel(instanceId, payload) {
13893
+ return input.registry.cancel(
13894
+ integrationToolIdempotencyKey({
13895
+ instanceId,
13896
+ turnRecordId: payload.turnRecordId,
13897
+ toolCallId: payload.toolCallId,
13898
+ toolName: payload.toolName
13899
+ })
13900
+ );
13901
+ },
13902
+ async handle(instanceId, payload) {
13903
+ const fail = (error) => ({
13904
+ turnRecordId: payload.turnRecordId,
13905
+ toolCallId: payload.toolCallId,
13906
+ ok: false,
13907
+ error
13908
+ });
13909
+ const process2 = input.repos.processes.getById(instanceId);
13910
+ const turn = input.repos.turnRecords.getById(payload.turnRecordId);
13911
+ if (!process2 || !turn || turn.instanceId !== instanceId || turn.status !== "running") {
13912
+ return fail("Integration tool call does not belong to the active running turn");
13913
+ }
13914
+ const currentStart = process2.currentExecution?.kind === "worker_start" ? input.repos.turnStarts.getById(process2.currentExecution.id) : null;
13915
+ const expectedTurnRecordId = currentStart?.state.kind === "accepted" ? currentStart.state.turnRecordId : null;
13916
+ if (expectedTurnRecordId !== payload.turnRecordId) {
13917
+ return fail("Integration tool call targets a stale turn record");
13918
+ }
13919
+ if (process2.selectedTurnId !== turn.turnId) {
13920
+ return fail("Integration tool call targets a stale turn");
13921
+ }
13922
+ const turnDefinition = input.processActionRegistry.getTurnDefinition(
13923
+ process2.processId,
13924
+ turn.turnId
13925
+ );
13926
+ if (turnDefinition?.kind !== "llm" || !turnDefinition.integrationTools?.includes(payload.toolName)) {
13927
+ return fail(`Integration tool '${payload.toolName}' is not authorized for this turn`);
13928
+ }
13929
+ const projects = input.repos.projects.listByInstance(instanceId);
13930
+ const projectKey = typeof payload.args.projectKey === "string" ? payload.args.projectKey : null;
13931
+ const project = projectKey ? projects.find((candidate) => candidate.key === projectKey) ?? null : null;
13932
+ if (projectKey && !project) return fail(`Unknown process project '${projectKey}'`);
13933
+ try {
13934
+ const result = await input.registry.execute(payload.toolName, payload.args, {
13935
+ process: process2,
13936
+ projects,
13937
+ turn,
13938
+ project,
13939
+ idempotencyKey: integrationToolIdempotencyKey({
13940
+ instanceId,
13941
+ turnRecordId: payload.turnRecordId,
13942
+ toolCallId: payload.toolCallId,
13943
+ toolName: payload.toolName
13944
+ })
13945
+ });
13946
+ return {
13947
+ turnRecordId: payload.turnRecordId,
13948
+ toolCallId: payload.toolCallId,
13949
+ ok: true,
13950
+ result
13951
+ };
13952
+ } catch (error) {
13953
+ return fail(error instanceof Error ? error.message : "Integration tool execution failed");
13954
+ }
13955
+ }
13956
+ };
13957
+ }
13958
+
13833
13959
  // src/launcher-model-config-service.ts
13834
13960
  import {
13835
13961
  findUiLauncherById
@@ -14421,7 +14547,7 @@ async function reconcilePersistedProcessModelIntegrity(input) {
14421
14547
  }
14422
14548
 
14423
14549
  // src/process-model-selection.ts
14424
- import { trimToNull as trimToNull3 } from "@leitwerk-dev/domain";
14550
+ import { trimToNull as trimToNull2 } from "@leitwerk-dev/domain";
14425
14551
  import {
14426
14552
  isLlmTurnDefinition as isLlmTurnDefinition5
14427
14553
  } from "@leitwerk-dev/process-sdk";
@@ -14587,7 +14713,7 @@ function createProcessModelSelection(deps) {
14587
14713
  return {
14588
14714
  kind: "not_applicable",
14589
14715
  turnId,
14590
- description: trimToNull3(candidateTurnDef?.description) ?? turnId
14716
+ description: trimToNull2(candidateTurnDef?.description) ?? turnId
14591
14717
  };
14592
14718
  }
14593
14719
  const policyResult = deps.processModelPolicy.evaluate({
@@ -14619,7 +14745,7 @@ function createProcessModelSelection(deps) {
14619
14745
  return {
14620
14746
  kind: "llm_turn",
14621
14747
  turnId,
14622
- description: trimToNull3(candidateTurnDef.description) ?? turnId,
14748
+ description: trimToNull2(candidateTurnDef.description) ?? turnId,
14623
14749
  resolvedModel: nextTurnModel.resolvedModel,
14624
14750
  warmPromptCache: nextTurnModel.warmPromptCache
14625
14751
  };
@@ -17301,7 +17427,8 @@ async function createConfiguredWorkerRunnerRuntime(input) {
17301
17427
  ...pod ? {
17302
17428
  annotations: pod.annotations,
17303
17429
  nodeSelector: pod.node_selector,
17304
- tolerations: pod.tolerations
17430
+ tolerations: pod.tolerations,
17431
+ hostAliases: pod.host_aliases
17305
17432
  } : {}
17306
17433
  }
17307
17434
  });
@@ -17433,6 +17560,7 @@ ${configErrors.join("\n")}`);
17433
17560
  const processOperations = createProcessOperationCoordinator();
17434
17561
  const processGraphs = extensionCatalog.processes;
17435
17562
  const processActionRegistry = buildProcessActionRegistry(extensionCatalog);
17563
+ const integrationTools = new IntegrationToolRegistry();
17436
17564
  const processUiRegistry = buildProcessUiRegistry(extensionCatalog);
17437
17565
  const processModelPolicy = createServerProcessModelPolicy({
17438
17566
  config,
@@ -17469,18 +17597,10 @@ ${configErrors.join("\n")}`);
17469
17597
  commitMessages: config.commit_messages,
17470
17598
  getModelProfilesForProcess
17471
17599
  });
17472
- const processWatcherConfigErrors = validateConfiguredProcessWatchersAgainstCatalog({
17473
- config,
17474
- catalog: extensionCatalog,
17475
- processModelPolicy
17476
- });
17477
- if (processWatcherConfigErrors.length > 0) {
17478
- throw new Error(`Invalid process watcher config:
17479
- ${processWatcherConfigErrors.join("\n")}`);
17480
- }
17481
17600
  const processWatcherService = buildProcessWatcherRegistry(extensionCatalog, config, {
17482
17601
  modelProfiles: launcherModelProfiles,
17483
- getModelProfilesForProcess
17602
+ getModelProfilesForProcess,
17603
+ processModelPolicy
17484
17604
  });
17485
17605
  const workerWebSocketIpc = createWorkerWebSocketIpcManager();
17486
17606
  workerWebSocketIpc.setUnknownWorkerConnectionsRetryable(true);
@@ -17736,6 +17856,11 @@ ${processWatcherConfigErrors.join("\n")}`);
17736
17856
  )
17737
17857
  )
17738
17858
  });
17859
+ const integrationToolRequests = createIntegrationToolRequestService({
17860
+ registry: integrationTools,
17861
+ repos: baseDeps,
17862
+ processActionRegistry
17863
+ });
17739
17864
  const ipcHandler = createIpcHandler(
17740
17865
  {
17741
17866
  processes: baseDeps.processes,
@@ -17744,6 +17869,8 @@ ${processWatcherConfigErrors.join("\n")}`);
17744
17869
  events: baseDeps.events,
17745
17870
  leases: baseDeps.leases,
17746
17871
  turnRecords: baseDeps.turnRecords,
17872
+ handleIntegrationToolRequest: (instanceId, payload) => integrationToolRequests.handle(instanceId, payload),
17873
+ handleIntegrationToolCancel: (instanceId, payload) => void integrationToolRequests.cancel(instanceId, payload),
17747
17874
  processQuestions,
17748
17875
  broadcaster,
17749
17876
  commands: processEngine,
@@ -17778,6 +17905,9 @@ ${processWatcherConfigErrors.join("\n")}`);
17778
17905
  },
17779
17906
  onCredentialUpdateResult(instanceId, workerId, payload) {
17780
17907
  supervisor?.credentialUpdateResult(instanceId, workerId, payload);
17908
+ },
17909
+ onIntegrationToolResult(instanceId, workerId, payload) {
17910
+ supervisor?.integrationToolResult(instanceId, workerId, payload);
17781
17911
  }
17782
17912
  }
17783
17913
  );
@@ -17810,13 +17940,8 @@ ${processWatcherConfigErrors.join("\n")}`);
17810
17940
  return piResourceBundles.get(digest);
17811
17941
  },
17812
17942
  resolveRepositoryCredentials: (input) => repositoryCredentials.resolveWorkerCredentials(input),
17813
- resolveCredential(providerId, options) {
17814
- const credential = modelProviderCredentials.resolve(providerId, options);
17815
- return credential && credential.revision !== null ? {
17816
- revision: credential.revision,
17817
- values: credential.values
17818
- } : null;
17819
- }
17943
+ integrationTools,
17944
+ resolveCredential: (providerId, options) => modelProviderCredentials.resolve(providerId, options)
17820
17945
  });
17821
17946
  let staleHeartbeatWatchdog = null;
17822
17947
  let retainedVolumeCleanupTimer = null;
@@ -17948,27 +18073,6 @@ ${processWatcherConfigErrors.join("\n")}`);
17948
18073
  broadcaster,
17949
18074
  logger: app.log
17950
18075
  });
17951
- const filesystemProcessWatchers = createFilesystemProcessWatchersService({
17952
- processWatchers: processWatcherService,
17953
- launchPlans,
17954
- launchExecutorDeps: {
17955
- commitMessages: config.commit_messages,
17956
- processes: baseDeps.processes,
17957
- projects: baseDeps.projects,
17958
- processSkills: baseDeps.processSkills,
17959
- handoffDedupKeys: baseDeps.handoffDedupKeys,
17960
- futureExecutions: baseDeps.futureExecutions,
17961
- transaction: baseDeps.transaction,
17962
- broadcaster,
17963
- commands: processEngine,
17964
- processTitles,
17965
- extensionHost,
17966
- logger: app.log
17967
- },
17968
- logger: app.log
17969
- });
17970
- startHooks.push(() => filesystemProcessWatchers.start());
17971
- stopHooks.push(() => filesystemProcessWatchers.stop());
17972
18076
  const processActionListDeps = {
17973
18077
  projects: baseDeps.projects,
17974
18078
  futureExecutions: baseDeps.futureExecutions,
@@ -18023,6 +18127,7 @@ ${processWatcherConfigErrors.join("\n")}`);
18023
18127
  provide: hostCapabilities.provide.bind(hostCapabilities),
18024
18128
  get: hostCapabilities.get.bind(hostCapabilities),
18025
18129
  require: hostCapabilities.require.bind(hostCapabilities),
18130
+ tool: (definition) => integrationTools.register(definition),
18026
18131
  onStart(handler) {
18027
18132
  startHooks.push(handler);
18028
18133
  },
@@ -18032,6 +18137,19 @@ ${processWatcherConfigErrors.join("\n")}`);
18032
18137
  },
18033
18138
  (id) => config.extensions?.[id]
18034
18139
  );
18140
+ for (const process2 of extensionCatalog.processes.values()) {
18141
+ for (const [turnId, binding] of process2.turns) {
18142
+ const definition = binding.definition;
18143
+ if (definition.kind !== "llm" || !definition.integrationTools?.length) continue;
18144
+ try {
18145
+ integrationTools.declarations(definition.integrationTools);
18146
+ } catch (error) {
18147
+ throw new Error(
18148
+ `Invalid integration tools for process '${process2.id}' turn '${turnId}': ${error instanceof Error ? error.message : String(error)}`
18149
+ );
18150
+ }
18151
+ }
18152
+ }
18035
18153
  markStartup("server_extensions");
18036
18154
  const deps = {
18037
18155
  ...baseDeps,
@@ -18160,7 +18278,6 @@ export {
18160
18278
  buildProcessTitleSourceFields,
18161
18279
  buildProcessTitlePrompt,
18162
18280
  createProcessTitleGenerator,
18163
- validateConfiguredProcessWatchersAgainstCatalog,
18164
18281
  buildProcessWatcherRegistry,
18165
18282
  ResultImageStore,
18166
18283
  registerUiRendererRoutes,
@@ -18174,4 +18291,4 @@ export {
18174
18291
  createApp,
18175
18292
  createAppContext
18176
18293
  };
18177
- //# sourceMappingURL=chunk-KVHAK5UR.js.map
18294
+ //# sourceMappingURL=chunk-UC3OOEQ3.js.map