@nanobpm/urban 0.96.2 → 0.97.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 (48) hide show
  1. package/README.md +32 -0
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/runtime/connector-worker-sdk.d.ts +2 -0
  5. package/dist/runtime/connector-worker-sdk.js +6 -1
  6. package/dist/runtime/core/host.d.ts +15 -5
  7. package/dist/runtime/core/manifest.d.ts +23 -0
  8. package/dist/runtime/core/manifest.js +8 -0
  9. package/dist/runtime/core/modules/connectors.d.ts +3 -0
  10. package/dist/runtime/core/modules/connectors.js +32 -1
  11. package/dist/runtime/core/modules/workers.js +5 -1
  12. package/dist/runtime/core/validate.js +12 -0
  13. package/dist/runtime/engine/nanosdk.d.ts +1 -0
  14. package/dist/runtime/engine/nanosdk.js +3 -0
  15. package/dist/runtime/index.d.ts +3 -3
  16. package/dist/runtime/index.js +1 -1
  17. package/dist/toolkit/gen.d.ts +10 -0
  18. package/dist/toolkit/gen.js +1 -1
  19. package/dist/toolkit/generate.js +9 -1
  20. package/dist/toolkit/models.d.ts +7 -0
  21. package/dist/toolkit/models.js +4 -1
  22. package/dist/toolkit/scaffold/workers.d.ts +9 -6
  23. package/dist/toolkit/scaffold/workers.js +13 -5
  24. package/dist/toolkit/scaffold.d.ts +17 -0
  25. package/dist/toolkit/scaffold.js +9 -2
  26. package/package.json +3 -3
  27. package/src/index.ts +1 -0
  28. package/src/runtime/connector-worker-sdk.test.ts +9 -0
  29. package/src/runtime/connector-worker-sdk.ts +8 -1
  30. package/src/runtime/core/host.ts +16 -1
  31. package/src/runtime/core/manifest.ts +28 -0
  32. package/src/runtime/core/modules/connectors.test.ts +158 -1
  33. package/src/runtime/core/modules/connectors.ts +44 -1
  34. package/src/runtime/core/modules/workers.test.ts +45 -1
  35. package/src/runtime/core/modules/workers.ts +5 -1
  36. package/src/runtime/core/validate.test.ts +19 -0
  37. package/src/runtime/core/validate.ts +12 -0
  38. package/src/runtime/engine/nanosdk.test.ts +17 -0
  39. package/src/runtime/engine/nanosdk.ts +4 -1
  40. package/src/runtime/index.ts +3 -0
  41. package/src/toolkit/gen.ts +11 -1
  42. package/src/toolkit/generate.test.ts +86 -1
  43. package/src/toolkit/generate.ts +9 -1
  44. package/src/toolkit/models.test.ts +21 -0
  45. package/src/toolkit/models.ts +10 -1
  46. package/src/toolkit/scaffold/workers.test.ts +65 -0
  47. package/src/toolkit/scaffold/workers.ts +14 -5
  48. package/src/toolkit/scaffold.ts +27 -1
@@ -240,6 +240,21 @@ export interface WorkerSubscription {
240
240
  unsubscribe(): Promise<void>;
241
241
  }
242
242
 
243
+ /** Options for {@link EngineClient.registerWorker}. */
244
+ export interface RegisterWorkerOptions {
245
+ /** Worker name reported to the engine. The adapter supplies a default. */
246
+ workerName?: string;
247
+ /** Max jobs the worker handles in parallel. The adapter supplies a default. */
248
+ maxParallelJobs?: number;
249
+ /** Job lock timeout, ms (issue #596): how long the engine leases an activated job to
250
+ * this worker before re-activating it elsewhere. Set it above the handler's worst-case
251
+ * runtime for long steps (transcription, an agent call, a multi-GB upload) so the lock
252
+ * cannot expire mid-handler and the job run twice. Absent ⇒ the engine/SDK default. */
253
+ timeoutMs?: number;
254
+ /** Restrict the variables surfaced to the handler to this subset (engine-side projection). */
255
+ fetchVariables?: string[];
256
+ }
257
+
243
258
  /**
244
259
  * A process instance's terminal-relevant lifecycle state, as the engine reports it.
245
260
  * `ACTIVE` (still running), `COMPLETED` (ended normally at an end event), or
@@ -991,7 +1006,7 @@ export interface EngineClient {
991
1006
  registerWorker(
992
1007
  jobType: string,
993
1008
  handler: JobHandler,
994
- options?: { workerName?: string; maxParallelJobs?: number; fetchVariables?: string[] },
1009
+ options?: RegisterWorkerOptions,
995
1010
  ): Promise<WorkerSubscription>;
996
1011
  /** Tear down all connections. */
997
1012
  close(): Promise<void>;
@@ -123,11 +123,39 @@ export function isConfiguredStatusSelector(v: unknown): v is readonly string[] {
123
123
  return Array.isArray(v) && v.length > 0 && v.every((s) => typeof s === "string" && s.length > 0);
124
124
  }
125
125
 
126
+ /**
127
+ * A worker declaration (`workers[]`) as the runtime consumes it: the schema-owned
128
+ * {@link Worker} plus the pending-schema `timeoutMs` field (issue #596) — the job lock
129
+ * timeout in ms, passed through `registerWorker` to `createJobWorker({ jobTimeoutMs })`.
130
+ * For a long-running step (transcription, an agent call, a multi-GB upload) the SDK's
131
+ * default lock expires mid-handler: the engine re-activates the job and a second worker
132
+ * runs it again, and the first worker's completion is rejected. Set `timeoutMs` above the
133
+ * handler's worst-case runtime to keep the lock for the whole step.
134
+ *
135
+ * Bridged locally — like {@link NetworkConfig} — until `@nanobpm/nano-app-schema` folds
136
+ * `timeoutMs` into the `worker` definition (the schema shape is owned by that package,
137
+ * ADR 0027, and CI bans `declare module` augmentation). Drop this augmentation and
138
+ * re-export `Worker` plainly once the dep bump lands (No Drift Surfaces).
139
+ */
140
+ export type WorkerDecl = Worker & {
141
+ /** Job lock timeout, ms. Must be a positive integer (the manifest validator enforces it). */
142
+ readonly timeoutMs?: number;
143
+ };
144
+
126
145
  /** The job type a worker subscribes to (schema key: `taskType`). */
127
146
  export function workerJobType(w: Worker): string | undefined {
128
147
  return w.taskType;
129
148
  }
130
149
 
150
+ /** A worker declaration's job lock timeout, or `undefined` when absent/invalid — the
151
+ * validator flags an invalid value, so a consumer treats it as unset rather than
152
+ * propagating a malformed lock to the engine. Read reflectively (like `network.bind`)
153
+ * because `timeoutMs` is pending-schema and not on the static {@link Worker} type. */
154
+ export function workerTimeoutMs(w: Worker): number | undefined {
155
+ const v: unknown = Reflect.get(w, "timeoutMs");
156
+ return typeof v === "number" && Number.isInteger(v) && v > 0 ? v : undefined;
157
+ }
158
+
131
159
  /**
132
160
  * The valid HTTP bind modes, in declaration order. This is the single runtime source of
133
161
  * truth for the set: {@link BindMode}, {@link isBindMode}, and the manifest validator
@@ -12,6 +12,11 @@ import { DataLayer } from "./datasource.ts";
12
12
  /** A tiny engine that records registrations and can deliver a job to a handler. */
13
13
  class MiniEngine implements EngineClient {
14
14
  workers = new Map<string, JobHandler>();
15
+ /** The options each `registerWorker` call carried, keyed by job type. */
16
+ workerOptions = new Map<
17
+ string,
18
+ { workerName?: string; maxParallelJobs?: number; timeoutMs?: number; fetchVariables?: string[] } | undefined
19
+ >();
15
20
  async deployResources(): Promise<{ deployed: number }> { return { deployed: 0 }; }
16
21
  async createInstance(): Promise<{ processInstanceKey: string }> { return { processInstanceKey: "pi" }; }
17
22
  async cancelInstance(): Promise<void> {}
@@ -34,8 +39,13 @@ class MiniEngine implements EngineClient {
34
39
  async resolveIncident(): Promise<void> {}
35
40
  async updateJobRetries(): Promise<void> {}
36
41
  async setVariables(): Promise<void> {}
37
- async registerWorker(jobType: string, handler: JobHandler): Promise<WorkerSubscription> {
42
+ async registerWorker(
43
+ jobType: string,
44
+ handler: JobHandler,
45
+ options?: { workerName?: string; maxParallelJobs?: number; timeoutMs?: number; fetchVariables?: string[] },
46
+ ): Promise<WorkerSubscription> {
38
47
  this.workers.set(jobType, handler);
48
+ this.workerOptions.set(jobType, options);
39
49
  return { jobType, unsubscribe: async () => void this.workers.delete(jobType) };
40
50
  }
41
51
  deliver(jobType: string, job: EngineJob) {
@@ -165,6 +175,153 @@ test("mountConnectors imports the pack entry and registers the drained worker",
165
175
  assert.deepEqual(out, { echoed: "hi" });
166
176
  });
167
177
 
178
+ test("mountConnectors carries a pack worker's defineWorker timeoutMs to registerWorker (issue #596)", async () => {
179
+ const engine = new MiniEngine();
180
+ const { ctx } = makeCtx(
181
+ { workers: [{ taskType: "slack:send-message", connector: PACK_ID }] },
182
+ engine,
183
+ {
184
+ files: slackFiles(),
185
+ onImport: () => {
186
+ defineWorker({
187
+ type: "slack:send-message",
188
+ timeoutMs: 900_000,
189
+ async handle(job) {
190
+ await job.complete({});
191
+ },
192
+ });
193
+ },
194
+ },
195
+ );
196
+ await mountConnectors(ctx, makeApp({ SLACK_BOT_TOKEN: "xoxb-1" }));
197
+ assert.equal(engine.workerOptions.get("slack:send-message")?.timeoutMs, 900_000);
198
+ });
199
+
200
+ test("mountConnectors falls back to the ext.json spec timeoutMs when defineWorker omits it (issue #596)", async () => {
201
+ const engine = new MiniEngine();
202
+ const files = slackFiles();
203
+ files[`/app/node_modules/${PKG}/nano-ide.ext.json`] = JSON.stringify({
204
+ id: PACK_ID,
205
+ workers: [
206
+ {
207
+ type: "slack:send-message",
208
+ entry: "worker.ts",
209
+ timeoutMs: 600_000,
210
+ configFields: [{ key: "botToken", env: "SLACK_BOT_TOKEN" }],
211
+ },
212
+ ],
213
+ });
214
+ const { ctx } = makeCtx(
215
+ { workers: [{ taskType: "slack:send-message", connector: PACK_ID }] },
216
+ engine,
217
+ {
218
+ files,
219
+ onImport: () => {
220
+ defineWorker({ type: "slack:send-message", async handle(job) { await job.complete({}); } });
221
+ },
222
+ },
223
+ );
224
+ await mountConnectors(ctx, makeApp({ SLACK_BOT_TOKEN: "xoxb-1" }));
225
+ assert.equal(engine.workerOptions.get("slack:send-message")?.timeoutMs, 600_000);
226
+ });
227
+
228
+ test("mountConnectors honours the manifest-declared timeoutMs for a connector worker (issue #596)", async () => {
229
+ const engine = new MiniEngine();
230
+ const { ctx } = makeCtx(
231
+ { workers: [{ taskType: "slack:send-message", connector: PACK_ID, timeoutMs: 3_600_000 }] },
232
+ engine,
233
+ {
234
+ files: slackFiles(),
235
+ onImport: () => {
236
+ defineWorker({ type: "slack:send-message", async handle(job) { await job.complete({}); } });
237
+ },
238
+ },
239
+ );
240
+ await mountConnectors(ctx, makeApp({ SLACK_BOT_TOKEN: "xoxb-1" }));
241
+ assert.equal(engine.workerOptions.get("slack:send-message")?.timeoutMs, 3_600_000);
242
+ });
243
+
244
+ test("mountConnectors connector timeout precedence: defineWorker > ext.json spec > manifest (issue #596)", async () => {
245
+ // Pack code wins over the ext.json spec, which wins over the manifest declaration.
246
+ const engine = new MiniEngine();
247
+ const files = slackFiles();
248
+ files[`/app/node_modules/${PKG}/nano-ide.ext.json`] = JSON.stringify({
249
+ id: PACK_ID,
250
+ workers: [
251
+ {
252
+ type: "slack:send-message",
253
+ entry: "worker.ts",
254
+ timeoutMs: 600_000,
255
+ configFields: [{ key: "botToken", env: "SLACK_BOT_TOKEN" }],
256
+ },
257
+ ],
258
+ });
259
+ const { ctx } = makeCtx(
260
+ { workers: [{ taskType: "slack:send-message", connector: PACK_ID, timeoutMs: 3_600_000 }] },
261
+ engine,
262
+ {
263
+ files,
264
+ onImport: () => {
265
+ defineWorker({
266
+ type: "slack:send-message",
267
+ timeoutMs: 900_000,
268
+ async handle(job) { await job.complete({}); },
269
+ });
270
+ },
271
+ },
272
+ );
273
+ await mountConnectors(ctx, makeApp({ SLACK_BOT_TOKEN: "xoxb-1" }));
274
+ assert.equal(engine.workerOptions.get("slack:send-message")?.timeoutMs, 900_000);
275
+ });
276
+
277
+ test("mountConnectors rejects a non-positive-integer defineWorker timeoutMs (issue #596)", async () => {
278
+ const engine = new MiniEngine();
279
+ const { ctx } = makeCtx(
280
+ { workers: [{ taskType: "slack:send-message", connector: PACK_ID }] },
281
+ engine,
282
+ {
283
+ files: slackFiles(),
284
+ onImport: () => {
285
+ defineWorker({ type: "slack:send-message", timeoutMs: 0, async handle(job) { await job.complete({}); } });
286
+ },
287
+ },
288
+ );
289
+ await assert.rejects(
290
+ () => mountConnectors(ctx, makeApp({ SLACK_BOT_TOKEN: "xoxb-1" })),
291
+ /defineWorker timeoutMs must be a positive integer/,
292
+ );
293
+ });
294
+
295
+ test("mountConnectors rejects a malformed ext.json spec timeoutMs (issue #596)", async () => {
296
+ const engine = new MiniEngine();
297
+ const files = slackFiles();
298
+ files[`/app/node_modules/${PKG}/nano-ide.ext.json`] = JSON.stringify({
299
+ id: PACK_ID,
300
+ workers: [
301
+ {
302
+ type: "slack:send-message",
303
+ entry: "worker.ts",
304
+ timeoutMs: -5,
305
+ configFields: [{ key: "botToken", env: "SLACK_BOT_TOKEN" }],
306
+ },
307
+ ],
308
+ });
309
+ const { ctx } = makeCtx(
310
+ { workers: [{ taskType: "slack:send-message", connector: PACK_ID }] },
311
+ engine,
312
+ {
313
+ files,
314
+ onImport: () => {
315
+ defineWorker({ type: "slack:send-message", async handle(job) { await job.complete({}); } });
316
+ },
317
+ },
318
+ );
319
+ await assert.rejects(
320
+ () => mountConnectors(ctx, makeApp({ SLACK_BOT_TOKEN: "xoxb-1" })),
321
+ /nano-ide\.ext\.json timeoutMs must be a positive integer/,
322
+ );
323
+ });
324
+
168
325
  test("mountConnectors skips a worker whose required env is unset", async () => {
169
326
  const engine = new MiniEngine();
170
327
  const { ctx, logs } = makeCtx(
@@ -18,7 +18,7 @@
18
18
  import type { AppApi, Mounted, RuntimeContext } from "../context.ts";
19
19
  import { errorMessage, isRecord } from "../guards.ts";
20
20
  import { BpmnError, type EngineJob, type JobHandler, type WorkerSubscription } from "../host.ts";
21
- import { workerJobType, type Worker } from "../manifest.ts";
21
+ import { workerJobType, workerTimeoutMs, type Worker } from "../manifest.ts";
22
22
  import {
23
23
  drainDefinedWorkers,
24
24
  type ConnectorWorkerJob,
@@ -39,6 +39,9 @@ interface PackWorkerSpec {
39
39
  type: string;
40
40
  entry: string;
41
41
  maxParallelJobs?: number;
42
+ /** Job lock timeout, ms (issue #596) — a design-time default the pack's
43
+ * `defineWorker({ timeoutMs })` overrides when both are set. */
44
+ timeoutMs?: number;
42
45
  configFields?: PackConfigField[];
43
46
  }
44
47
 
@@ -172,6 +175,32 @@ export function adaptConnectorHandler(worker: DefinedConnectorWorker): JobHandle
172
175
  };
173
176
  }
174
177
 
178
+ /**
179
+ * Validate a connector worker's job lock timeout (issue #596) before it reaches the
180
+ * engine. Unlike a manifest `workers[].timeoutMs` (author-time validated by
181
+ * `collectManifestIssues`) or a `w.run({ timeoutMs })` (validated at flow build), a
182
+ * connector timeout arrives from a THIRD-PARTY pack — `defineWorker({ timeoutMs })`
183
+ * in pack code or the `timeoutMs` field of its `nano-ide.ext.json` — with no
184
+ * validating gate in between. A zero/negative lock would expire instantly (the job
185
+ * re-activated mid-handler ⇒ duplicate execution) and a non-integer is a pack typo;
186
+ * fail closed at registration, naming the source, rather than propagate either to
187
+ * the engine.
188
+ */
189
+ function validateConnectorTimeout(
190
+ value: number,
191
+ source: string,
192
+ jobType: string,
193
+ packId: string,
194
+ ): number {
195
+ if (!Number.isInteger(value) || value <= 0) {
196
+ throw new Error(
197
+ `connector worker "${jobType}" (pack "${packId}"): ${source} timeoutMs must be a ` +
198
+ `positive integer (ms), got ${JSON.stringify(value)}`,
199
+ );
200
+ }
201
+ return value;
202
+ }
203
+
175
204
  /**
176
205
  * Mount every enabled connector worker (`workers[]` entries carrying a
177
206
  * `connector` field). Fails closed on a seam mismatch (an enabled connector whose
@@ -259,11 +288,25 @@ export async function mountConnectors(ctx: RuntimeContext, app: AppApi): Promise
259
288
  { instanceKey: job.processInstanceKey, elementId: job.elementId, jobType },
260
289
  () => inner(job),
261
290
  );
291
+ // Job lock timeout (issue #596) precedence, first declared wins:
292
+ // 1. the pack's `defineWorker({ timeoutMs })` — the authoritative runtime value
293
+ // 2. the pack's `nano-ide.ext.json` spec — the pack's design-time default
294
+ // 3. the app manifest's `workers[].timeoutMs` — the app author's declaration
295
+ // (mirrors the maxParallelJobs precedence below). The manifest value is already
296
+ // author-time validated (`collectManifestIssues`); the two pack-supplied values
297
+ // are validated here before either reaches the engine as a lock horizon.
298
+ const timeoutMs =
299
+ worker.timeoutMs !== undefined
300
+ ? validateConnectorTimeout(worker.timeoutMs, "defineWorker", jobType, packId)
301
+ : spec.timeoutMs !== undefined
302
+ ? validateConnectorTimeout(spec.timeoutMs, "nano-ide.ext.json", jobType, packId)
303
+ : workerTimeoutMs(decl);
262
304
  const sub = await ctx.engine.registerWorker(jobType, wrapped, {
263
305
  workerName: `${ctx.manifest.id}:${jobType}`,
264
306
  // The pack's `defineWorker({ maxParallelJobs })` is the authoritative runtime
265
307
  // value; the ext.json spec is a design-time default when the code omits it.
266
308
  maxParallelJobs: worker.maxParallelJobs ?? spec.maxParallelJobs,
309
+ timeoutMs,
267
310
  });
268
311
  subs.push(sub);
269
312
  jobTypes.push(jobType);
@@ -23,6 +23,11 @@ import { join } from "node:path";
23
23
  /** A tiny engine that records registrations and can deliver a job to a handler. */
24
24
  class MiniEngine implements EngineClient {
25
25
  workers = new Map<string, JobHandler>();
26
+ /** The options each `registerWorker` call carried, keyed by job type. */
27
+ workerOptions = new Map<
28
+ string,
29
+ { workerName?: string; maxParallelJobs?: number; timeoutMs?: number; fetchVariables?: string[] } | undefined
30
+ >();
26
31
  async deployResources(): Promise<{ deployed: number }> { return { deployed: 0 }; }
27
32
  async createInstance(): Promise<{ processInstanceKey: string }> { return { processInstanceKey: "pi" }; }
28
33
  async cancelInstance(): Promise<void> {}
@@ -46,8 +51,13 @@ class MiniEngine implements EngineClient {
46
51
  async updateJobRetries(): Promise<void> {}
47
52
  async setVariables(): Promise<void> {}
48
53
  async close(): Promise<void> {}
49
- async registerWorker(jobType: string, handler: JobHandler): Promise<WorkerSubscription> {
54
+ async registerWorker(
55
+ jobType: string,
56
+ handler: JobHandler,
57
+ options?: { workerName?: string; maxParallelJobs?: number; timeoutMs?: number; fetchVariables?: string[] },
58
+ ): Promise<WorkerSubscription> {
50
59
  this.workers.set(jobType, handler);
60
+ this.workerOptions.set(jobType, options);
51
61
  return { jobType, unsubscribe: async () => void this.workers.delete(jobType) };
52
62
  }
53
63
  deliver(jobType: string, job: EngineJob) {
@@ -226,6 +236,40 @@ test("mountWorkers silently skips a connector-backed worker (mountConnectors own
226
236
  assert.ok(!logs.some((l) => l.msg.includes("neither a handler nor an llm")));
227
237
  });
228
238
 
239
+ test("mountWorkers passes a worker's declared job lock timeout (timeoutMs) to registerWorker (issue #596)", async () => {
240
+ const engine = new MiniEngine();
241
+ const { ctx } = makeCtx(
242
+ {
243
+ workers: [
244
+ { taskType: "transcribe", handler: "workers/transcribe.ts", timeoutMs: 600_000 },
245
+ { taskType: "quick", handler: "workers/quick.ts" },
246
+ ],
247
+ llm: { fast: { provider: "env", model: "${NANO_APP_LLM_MODEL}" } },
248
+ },
249
+ engine,
250
+ );
251
+ ctx.host.importModule = async () => ({ default: () => ({}) });
252
+ await mountWorkers(ctx, makeApp());
253
+ assert.equal(engine.workerOptions.get("transcribe")?.timeoutMs, 600_000);
254
+ // A worker with no declared timeout leaves the engine/SDK default lock in place.
255
+ assert.equal(engine.workerOptions.get("quick")?.timeoutMs, undefined);
256
+ });
257
+
258
+ test("mountWorkers passes an llm worker's declared timeoutMs to registerWorker (issue #596)", async () => {
259
+ const engine = new MiniEngine();
260
+ const { ctx } = makeCtx(
261
+ {
262
+ workers: [{ taskType: "summarize", llm: "fast", timeoutMs: 300_000 }],
263
+ llm: { fast: { provider: "env", model: "${NANO_APP_LLM_MODEL}" } },
264
+ },
265
+ engine,
266
+ );
267
+ await withFetch("{}", async () => {
268
+ await mountWorkers(ctx, makeApp());
269
+ });
270
+ assert.equal(engine.workerOptions.get("summarize")?.timeoutMs, 300_000);
271
+ });
272
+
229
273
  test("mountWorkers binds the job's correlation context onto the handler's app.log", async () => {
230
274
  const engine = new MiniEngine();
231
275
  const { ctx } = makeCtx({ workers: [{ taskType: "charge", handler: "workers/charge.ts" }] }, engine);
@@ -5,7 +5,7 @@
5
5
  import type { AppApi, Mounted, RuntimeContext } from "../context.ts";
6
6
  import { isRecord } from "../guards.ts";
7
7
  import type { EngineJob, JobHandler, WorkerSubscription } from "../host.ts";
8
- import { workerJobType, type Worker } from "../manifest.ts";
8
+ import { workerJobType, workerTimeoutMs, type Worker } from "../manifest.ts";
9
9
  import { type DecisionEvaluator, type LlmRuntime, runLlmJob } from "./llm.ts";
10
10
  import { runInJobContext } from "../execContext.ts";
11
11
  import type { JobExecContext } from "../execContext.ts";
@@ -326,6 +326,8 @@ export async function mountWorkers(
326
326
  };
327
327
  const sub = await ctx.engine.registerWorker(jobType, wrapped, {
328
328
  workerName: `${ctx.manifest.id}:${jobType}`,
329
+ // The declared job lock timeout (issue #596) — absent ⇒ the engine/SDK default.
330
+ timeoutMs: workerTimeoutMs(decl),
329
331
  });
330
332
  subs.push(sub);
331
333
  jobTypes.push(jobType);
@@ -349,6 +351,8 @@ export async function mountWorkers(
349
351
  };
350
352
  const sub = await ctx.engine.registerWorker(jobType, wrapped, {
351
353
  workerName: `${ctx.manifest.id}:${jobType}`,
354
+ // The declared job lock timeout (issue #596) — absent ⇒ the engine/SDK default.
355
+ timeoutMs: workerTimeoutMs(decl),
352
356
  });
353
357
  subs.push(sub);
354
358
  jobTypes.push(jobType);
@@ -100,6 +100,25 @@ test("an llm-backed worker (no handler) is accepted", () => {
100
100
  assert.ok(!issues.some((i) => i.path.startsWith("workers[0]")));
101
101
  });
102
102
 
103
+ test("a worker job lock timeout (timeoutMs) must be a positive integer (issue #596)", () => {
104
+ const ok = collectManifestIssues({
105
+ ...valid,
106
+ workers: [{ taskType: "a.b", handler: "workers/x.ts", timeoutMs: 600_000 }],
107
+ });
108
+ assert.ok(!ok.some((i) => i.path.startsWith("workers[0]")));
109
+
110
+ for (const bad of [0, -5, 1.5, Number.NaN, "600000"]) {
111
+ const issues = collectManifestIssues({
112
+ ...valid,
113
+ workers: [{ taskType: "a.b", handler: "workers/x.ts", timeoutMs: bad }],
114
+ });
115
+ assert.ok(
116
+ issues.some((i) => i.path === "workers[0].timeoutMs"),
117
+ `timeoutMs=${String(bad)} must be rejected`,
118
+ );
119
+ }
120
+ });
121
+
103
122
  test("data.default must reference an existing source", () => {
104
123
  const issues = collectManifestIssues({
105
124
  ...valid,
@@ -144,6 +144,18 @@ export function collectManifestIssues(m: unknown): ValidationIssue[] {
144
144
  });
145
145
  }
146
146
  }
147
+ // The pending-schema job lock timeout (issue #596): when present it must be a
148
+ // positive integer of ms — a zero/negative lock would expire instantly (the job
149
+ // re-activated mid-handler), and a non-integer is a manifest typo to fail fast on.
150
+ if (worker !== undefined && "timeoutMs" in worker) {
151
+ const t = worker.timeoutMs;
152
+ if (typeof t !== "number" || !Number.isInteger(t) || t <= 0) {
153
+ issues.push({
154
+ path: `workers[${i}].timeoutMs`,
155
+ message: "timeoutMs must be a positive integer (ms)",
156
+ });
157
+ }
158
+ }
147
159
  });
148
160
  }
149
161
 
@@ -1211,6 +1211,23 @@ test("registerWorker creates a worker the SDK auto-starts, and dispatches + comp
1211
1211
  assert.equal(rec.stopped, 1);
1212
1212
  });
1213
1213
 
1214
+ test("registerWorker passes the job lock timeout through to createJobWorker (issue #596)", async () => {
1215
+ const client = fakeSdkClient();
1216
+ const engine = new SdkEngineClient(client);
1217
+ await engine.registerWorker("svc", () => ({}), { timeoutMs: 600_000 });
1218
+ const rec = client.workers[0];
1219
+ assert.equal(rec.cfg.jobTimeoutMs, 600_000);
1220
+ });
1221
+
1222
+ test("registerWorker leaves jobTimeoutMs unset (SDK default lock) when no timeoutMs is given", async () => {
1223
+ const client = fakeSdkClient();
1224
+ const engine = new SdkEngineClient(client);
1225
+ await engine.registerWorker("svc", () => ({}));
1226
+ const rec = client.workers[0];
1227
+ assert.equal(rec.cfg.jobTimeoutMs, undefined);
1228
+ assert.equal("jobTimeoutMs" in rec.cfg, false);
1229
+ });
1230
+
1214
1231
  test("registerWorker fails the job when the handler throws", async () => {
1215
1232
  const client = fakeSdkClient();
1216
1233
  const engine = new SdkEngineClient(client);
@@ -1366,12 +1366,15 @@ export class SdkEngineClient implements EngineClient {
1366
1366
  async registerWorker(
1367
1367
  jobType: string,
1368
1368
  handler: JobHandler,
1369
- options?: { workerName?: string; maxParallelJobs?: number; fetchVariables?: string[] },
1369
+ options?: { workerName?: string; maxParallelJobs?: number; timeoutMs?: number; fetchVariables?: string[] },
1370
1370
  ): Promise<WorkerSubscription> {
1371
1371
  const worker = this.client.createJobWorker({
1372
1372
  jobType,
1373
1373
  workerName: options?.workerName ?? `urban:${jobType}`,
1374
1374
  maxParallelJobs: options?.maxParallelJobs ?? 8,
1375
+ // The job lock timeout (issue #596): pass it through only when declared, so an
1376
+ // undeclared worker keeps the SDK's default lock rather than an explicit value.
1377
+ ...(options?.timeoutMs !== undefined ? { jobTimeoutMs: options.timeoutMs } : {}),
1375
1378
  fetchVariables: options?.fetchVariables,
1376
1379
  jobHandler: async (job) => {
1377
1380
  const rawKey = job.jobKey;
@@ -50,6 +50,7 @@ export {
50
50
  resolveBindHost,
51
51
  resolveBindMode,
52
52
  workerJobType,
53
+ workerTimeoutMs,
53
54
  ALL_INTERFACES_HOST,
54
55
  BIND_ENV_VAR,
55
56
  LOOPBACK_HOST,
@@ -70,6 +71,7 @@ export type {
70
71
  TaskInboxSurface,
71
72
  Trigger,
72
73
  Worker,
74
+ WorkerDecl,
73
75
  } from "./core/manifest.ts";
74
76
 
75
77
  // Validation
@@ -112,6 +114,7 @@ export type {
112
114
  ProcessDefinitionIdentity,
113
115
  ProcessInstanceSnapshot,
114
116
  ProcessInstanceState,
117
+ RegisterWorkerOptions,
115
118
  SqliteDb,
116
119
  UserTaskState,
117
120
  UserTaskSummary,
@@ -65,6 +65,16 @@ export interface GenResult {
65
65
  incomplete: boolean;
66
66
  /** Per-file model-derivation errors (empty on success). */
67
67
  modelErrors: ModelError[];
68
+ /** Job types of inline-handled (`w.run`) code-first steps — the set the app's in-process
69
+ * Worker already serves (nano-ide#595). The worker-stub scaffolder skips these; empty for a
70
+ * model-first app. */
71
+ inlineTaskTypes: string[];
72
+ /** The code-first models derived in-memory this run (`deriveModels().models`) — the
73
+ * worker-stub scaffolder plans against these in addition to the on-disk models, since a
74
+ * declared `models` block (e.g. `models.workflows`) suppresses the `resources/` convention
75
+ * scan that would otherwise pick the written `.bpmn` up (nano-ide#595). Empty for a
76
+ * model-first app. */
77
+ derivedModels: ModelSource[];
68
78
  /** Non-fatal spec-hygiene warnings (e.g. a requestBody schema shared by >1 operation). Empty on
69
79
  * a clean spec. Surfaced by the CLI but never fail gen/check — advisory only. */
70
80
  warnings: string[];
@@ -333,7 +343,7 @@ export async function runGen(opts: GenOptions & { check?: boolean }): Promise<Ge
333
343
  }
334
344
  }
335
345
 
336
- return { artifacts, drift, swept: swept.sort(), incomplete: derived.incomplete, modelErrors: derived.errors, warnings };
346
+ return { artifacts, drift, swept: swept.sort(), incomplete: derived.incomplete, modelErrors: derived.errors, inlineTaskTypes: derived.inlineTaskTypes, derivedModels: derived.models, warnings };
337
347
  }
338
348
 
339
349
  export { dirOf, join as joinPath };
@@ -2,9 +2,13 @@ import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
3
  import { generate } from "./generate.ts";
4
4
  import type { GenIO } from "./gen.ts";
5
+ import { defineFlow, envelope } from "@nanobpm/workflow";
5
6
 
6
7
  /** In-memory filesystem mirroring gen.test.ts's memIO (IO-free, deterministic). */
7
- function memIO(files: Record<string, string>): GenIO & { files: Record<string, string> } {
8
+ function memIO(
9
+ files: Record<string, string>,
10
+ modules: Record<string, Record<string, unknown>> = {},
11
+ ): GenIO & { files: Record<string, string> } {
8
12
  return {
9
13
  files,
10
14
  async readText(p) {
@@ -25,12 +29,28 @@ function memIO(files: Record<string, string>): GenIO & { files: Record<string, s
25
29
  }
26
30
  return [...names];
27
31
  },
32
+ async listSubdirs(p) {
33
+ const prefix = p.replace(/\/+$/, "") + "/";
34
+ const names = new Set<string>();
35
+ for (const f of Object.keys(files)) {
36
+ if (f.startsWith(prefix)) {
37
+ const rest = f.slice(prefix.length);
38
+ const slash = rest.indexOf("/");
39
+ if (slash > 0) names.add(rest.slice(0, slash));
40
+ }
41
+ }
42
+ return [...names];
43
+ },
28
44
  async exists(p) {
29
45
  return p in files;
30
46
  },
31
47
  async remove(p) {
32
48
  delete files[p];
33
49
  },
50
+ async importModule(p) {
51
+ if (!(p in modules)) throw new Error(`no module registered for ${p}`);
52
+ return modules[p];
53
+ },
34
54
  };
35
55
  }
36
56
 
@@ -133,3 +153,68 @@ test("generate keeps existing human-owned stubs (write-once, never clobbered)",
133
153
  assert.deepEqual(res.operationStubs.map((s) => s.status), ["kept"]);
134
154
  assert.deepEqual(res.missingStubs, []);
135
155
  });
156
+
157
+ // --- code-first: w.run steps are inline-handled, so gen must never scaffold stubs for them ---
158
+
159
+ const GreetIn = envelope("GreetIn", { who: "string" });
160
+ const GreetOut = envelope("GreetOut", { message: "string" });
161
+
162
+ /** The stock code-first template's flow: one inline-handled `w.run` step (nano-ide#595's repro). */
163
+ const greetFlow = defineFlow("greet", { hello: { in: GreetIn, out: GreetOut } }, (w) => {
164
+ w.run("hello", async () => ({ message: "hi" }));
165
+ });
166
+
167
+ test("generate on a code-first app scaffolds NO stub for an inline w.run step (nano-ide#595)", async () => {
168
+ // The stock code-first app (create-urban-app --code-first): `greet:hello` is served by
169
+ // `w.run("hello", …)` and hosted in-process by main.ts's Worker. Scaffolding a throwing stub
170
+ // for it puts a second, always-failing worker on the same job type.
171
+ const io = memIO(
172
+ {
173
+ "/cf/nano.app.json": JSON.stringify({
174
+ id: "cf",
175
+ data: { default: "app" },
176
+ models: { workflows: ["workflows/*.ts"] },
177
+ }),
178
+ "/cf/workflows/greet.ts": "// derived in-memory via importModule stub",
179
+ },
180
+ { "/cf/workflows/greet.ts": { greet: greetFlow } },
181
+ );
182
+
183
+ const res = await generate({ root: "/cf", io });
184
+
185
+ assert.equal(res.incomplete, false);
186
+ assert.deepEqual(res.workerStubs, [], "no worker stub is scaffolded for an inline-handled step");
187
+ assert.deepEqual(res.wiredWorkers, [], "nothing is wired into workers[]");
188
+ assert.equal(res.manifestPatched, false, "the manifest is untouched");
189
+ assert.equal(io.files["/cf/workers/greet-hello/worker.ts"], undefined, "no throwing stub on disk");
190
+ const manifest = JSON.parse(io.files["/cf/nano.app.json"]);
191
+ assert.equal(manifest.workers, undefined, "workers[] stays undeclared");
192
+ // The model itself is still derived and written.
193
+ assert.ok(io.files["/cf/resources/processes/greet.bpmn"], "the derived .bpmn still lands");
194
+ });
195
+
196
+ test("generate on a code-first app still scaffolds a stub for an external w.task step", async () => {
197
+ // The other half of the split: only `w.run` steps are inline; a `w.task` step has no in-process
198
+ // handler, so it still needs its write-once stub.
199
+ const flow = defineFlow("orders", (w) => {
200
+ w.run("charge", async () => ({}));
201
+ w.task("sign"); // external worker
202
+ });
203
+ const io = memIO(
204
+ {
205
+ "/cf/nano.app.json": JSON.stringify({
206
+ id: "cf",
207
+ data: { default: "app" },
208
+ models: { workflows: ["workflows/*.ts"] },
209
+ }),
210
+ "/cf/workflows/orders.ts": "// derived in-memory via importModule stub",
211
+ },
212
+ { "/cf/workflows/orders.ts": { flow } },
213
+ );
214
+
215
+ const res = await generate({ root: "/cf", io });
216
+
217
+ assert.deepEqual(res.workerStubs.map((s) => s.taskType), ["orders:sign"]);
218
+ assert.ok(io.files["/cf/workers/orders-sign/worker.ts"], "external task gets its stub");
219
+ assert.equal(io.files["/cf/workers/orders-charge/worker.ts"], undefined, "inline step gets none");
220
+ });