@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
package/README.md CHANGED
@@ -210,6 +210,38 @@ wiring; `WorkflowClient` deploys and starts, `Worker` hosts your `run` steps.
210
210
  inspectable in a modeller/Operate — `@nanobpm/urban` bundles `bpmn-auto-layout`
211
211
  so this works out of the box.
212
212
 
213
+ For a long-running step (transcription, an agent call, a multi-GB upload),
214
+ declare a job lock timeout so the engine's lease cannot expire mid-handler and
215
+ the job run twice — per step with `w.run(name, handler, { timeoutMs })`, or
216
+ worker-wide with `new Worker({ jobTimeoutMs })`:
217
+
218
+ ```ts
219
+ const flow = defineFlow("uploads", (w) => {
220
+ w.run("transcode", transcode, { timeoutMs: 3_600_000 }); // 1h lock for this step
221
+ w.run("notify", notify); // worker-wide default (30s) applies
222
+ });
223
+ ```
224
+
225
+ Manifest-declared workers get the same knob as `timeoutMs` on the `workers[]`
226
+ entry (validated as a positive integer of ms):
227
+
228
+ ```jsonc
229
+ // nano.app.json
230
+ {
231
+ "workers": [
232
+ { "taskType": "media.transcode", "handler": "workers/transcode.ts", "timeoutMs": 3600000 }
233
+ ]
234
+ }
235
+ ```
236
+
237
+ Connector-backed workers resolve the lock timeout from three sources, first
238
+ declared wins: the pack's `defineWorker({ timeoutMs })` (authoritative runtime
239
+ value), then the pack's `nano-ide.ext.json` worker `timeoutMs` (design-time
240
+ default), then the app manifest's `workers[].timeoutMs`. Pack-supplied values
241
+ are validated at registration (a non-positive-integer fails the mount, naming
242
+ the source); the manifest value is validated at author time like any other
243
+ worker.
244
+
213
245
  ### Deploy by convention (`resources/`)
214
246
 
215
247
  Deployables are discovered by convention: with **no `models`** block in the
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export * from "./runtime/index.ts";
2
2
  export { createCamundaClient } from "@nanobpm/nano-sdk";
3
3
  export * from "./toolkit/index.ts";
4
- export { defineFlow, declarativeToBpmn, declarativeToLayoutedBpmn, externalJobTypes, envelope, layoutBpmn, toBpmn, toDeployableBpmn, Worker, WorkflowClient, WorkflowError, } from "@nanobpm/workflow";
4
+ export { defineFlow, declarativeToBpmn, declarativeToLayoutedBpmn, externalJobTypes, inlineJobTypes, envelope, layoutBpmn, toBpmn, toDeployableBpmn, Worker, WorkflowClient, WorkflowError, } from "@nanobpm/workflow";
5
5
  export type { FlowBuilder, TimerStart, Envelope, EnvelopeType, EnvelopeField, FieldSpec, ScalarType, WorkflowClientOptions, NanoSdkClient, NanoJobWorker, JobWorkerConfig, ActivatedJob, WorkerOptions, ActivityEvent, } from "@nanobpm/workflow";
package/dist/index.js CHANGED
@@ -22,4 +22,4 @@ export { createCamundaClient } from "@nanobpm/nano-sdk";
22
22
  // Toolkit — derivation library (`urban gen`)
23
23
  export * from "./toolkit/index.js";
24
24
  // Code-first process surface (re-exported from @nanobpm/workflow)
25
- export { defineFlow, declarativeToBpmn, declarativeToLayoutedBpmn, externalJobTypes, envelope, layoutBpmn, toBpmn, toDeployableBpmn, Worker, WorkflowClient, WorkflowError, } from "@nanobpm/workflow";
25
+ export { defineFlow, declarativeToBpmn, declarativeToLayoutedBpmn, externalJobTypes, inlineJobTypes, envelope, layoutBpmn, toBpmn, toDeployableBpmn, Worker, WorkflowClient, WorkflowError, } from "@nanobpm/workflow";
@@ -28,6 +28,8 @@ export interface ConnectorWorkerOptions {
28
28
  export interface DefinedConnectorWorker {
29
29
  type: string;
30
30
  maxParallelJobs?: number;
31
+ /** Job lock timeout, ms (issue #596) — carried from `defineWorker({ timeoutMs })`. */
32
+ timeoutMs?: number;
31
33
  handle: ConnectorWorkerOptions["handle"];
32
34
  }
33
35
  /** The `@nanobpm/worker` entrypoint the pack calls. Records the handler; does not
@@ -29,7 +29,12 @@ export function defineWorker(opts) {
29
29
  if (typeof opts.handle !== "function") {
30
30
  throw new Error(`defineWorker("${opts.type}"): handle must be a function`);
31
31
  }
32
- registered.push({ type: opts.type, maxParallelJobs: opts.maxParallelJobs, handle: opts.handle });
32
+ registered.push({
33
+ type: opts.type,
34
+ maxParallelJobs: opts.maxParallelJobs,
35
+ timeoutMs: opts.timeoutMs,
36
+ handle: opts.handle,
37
+ });
33
38
  }
34
39
  /** Return every worker registered since the last drain, and clear the registry.
35
40
  * The runtime calls this immediately after importing one pack entry, so the
@@ -201,6 +201,20 @@ export interface WorkerSubscription {
201
201
  readonly jobType: string;
202
202
  unsubscribe(): Promise<void>;
203
203
  }
204
+ /** Options for {@link EngineClient.registerWorker}. */
205
+ export interface RegisterWorkerOptions {
206
+ /** Worker name reported to the engine. The adapter supplies a default. */
207
+ workerName?: string;
208
+ /** Max jobs the worker handles in parallel. The adapter supplies a default. */
209
+ maxParallelJobs?: number;
210
+ /** Job lock timeout, ms (issue #596): how long the engine leases an activated job to
211
+ * this worker before re-activating it elsewhere. Set it above the handler's worst-case
212
+ * runtime for long steps (transcription, an agent call, a multi-GB upload) so the lock
213
+ * cannot expire mid-handler and the job run twice. Absent ⇒ the engine/SDK default. */
214
+ timeoutMs?: number;
215
+ /** Restrict the variables surfaced to the handler to this subset (engine-side projection). */
216
+ fetchVariables?: string[];
217
+ }
204
218
  /**
205
219
  * A process instance's terminal-relevant lifecycle state, as the engine reports it.
206
220
  * `ACTIVE` (still running), `COMPLETED` (ended normally at an end event), or
@@ -910,11 +924,7 @@ export interface EngineClient {
910
924
  local?: boolean;
911
925
  }): Promise<void>;
912
926
  /** Register a push worker for a job type. Draining is handled by the adapter. */
913
- registerWorker(jobType: string, handler: JobHandler, options?: {
914
- workerName?: string;
915
- maxParallelJobs?: number;
916
- fetchVariables?: string[];
917
- }): Promise<WorkerSubscription>;
927
+ registerWorker(jobType: string, handler: JobHandler, options?: RegisterWorkerOptions): Promise<WorkerSubscription>;
918
928
  /** Tear down all connections. */
919
929
  close(): Promise<void>;
920
930
  }
@@ -84,8 +84,31 @@ export type InstanceTracking = SchemaInstanceTracking & {
84
84
  * characters, or `activeStatuses.map(...)` crash on a non-array).
85
85
  */
86
86
  export declare function isConfiguredStatusSelector(v: unknown): v is readonly string[];
87
+ /**
88
+ * A worker declaration (`workers[]`) as the runtime consumes it: the schema-owned
89
+ * {@link Worker} plus the pending-schema `timeoutMs` field (issue #596) — the job lock
90
+ * timeout in ms, passed through `registerWorker` to `createJobWorker({ jobTimeoutMs })`.
91
+ * For a long-running step (transcription, an agent call, a multi-GB upload) the SDK's
92
+ * default lock expires mid-handler: the engine re-activates the job and a second worker
93
+ * runs it again, and the first worker's completion is rejected. Set `timeoutMs` above the
94
+ * handler's worst-case runtime to keep the lock for the whole step.
95
+ *
96
+ * Bridged locally — like {@link NetworkConfig} — until `@nanobpm/nano-app-schema` folds
97
+ * `timeoutMs` into the `worker` definition (the schema shape is owned by that package,
98
+ * ADR 0027, and CI bans `declare module` augmentation). Drop this augmentation and
99
+ * re-export `Worker` plainly once the dep bump lands (No Drift Surfaces).
100
+ */
101
+ export type WorkerDecl = Worker & {
102
+ /** Job lock timeout, ms. Must be a positive integer (the manifest validator enforces it). */
103
+ readonly timeoutMs?: number;
104
+ };
87
105
  /** The job type a worker subscribes to (schema key: `taskType`). */
88
106
  export declare function workerJobType(w: Worker): string | undefined;
107
+ /** A worker declaration's job lock timeout, or `undefined` when absent/invalid — the
108
+ * validator flags an invalid value, so a consumer treats it as unset rather than
109
+ * propagating a malformed lock to the engine. Read reflectively (like `network.bind`)
110
+ * because `timeoutMs` is pending-schema and not on the static {@link Worker} type. */
111
+ export declare function workerTimeoutMs(w: Worker): number | undefined;
89
112
  /**
90
113
  * The valid HTTP bind modes, in declaration order. This is the single runtime source of
91
114
  * truth for the set: {@link BindMode}, {@link isBindMode}, and the manifest validator
@@ -25,6 +25,14 @@ export function isConfiguredStatusSelector(v) {
25
25
  export function workerJobType(w) {
26
26
  return w.taskType;
27
27
  }
28
+ /** A worker declaration's job lock timeout, or `undefined` when absent/invalid — the
29
+ * validator flags an invalid value, so a consumer treats it as unset rather than
30
+ * propagating a malformed lock to the engine. Read reflectively (like `network.bind`)
31
+ * because `timeoutMs` is pending-schema and not on the static {@link Worker} type. */
32
+ export function workerTimeoutMs(w) {
33
+ const v = Reflect.get(w, "timeoutMs");
34
+ return typeof v === "number" && Number.isInteger(v) && v > 0 ? v : undefined;
35
+ }
28
36
  /**
29
37
  * The valid HTTP bind modes, in declaration order. This is the single runtime source of
30
38
  * truth for the set: {@link BindMode}, {@link isBindMode}, and the manifest validator
@@ -13,6 +13,9 @@ interface PackWorkerSpec {
13
13
  type: string;
14
14
  entry: string;
15
15
  maxParallelJobs?: number;
16
+ /** Job lock timeout, ms (issue #596) — a design-time default the pack's
17
+ * `defineWorker({ timeoutMs })` overrides when both are set. */
18
+ timeoutMs?: number;
16
19
  configFields?: PackConfigField[];
17
20
  }
18
21
  /** The pack manifest (`nano-ide.ext.json`) fields the runtime reads. */
@@ -16,7 +16,7 @@
16
16
  // the pack's `@nanobpm/worker` import live behind `host.importConnectorModule`.
17
17
  import { errorMessage, isRecord } from "../guards.js";
18
18
  import { BpmnError } from "../host.js";
19
- import { workerJobType } from "../manifest.js";
19
+ import { workerJobType, workerTimeoutMs } from "../manifest.js";
20
20
  import { drainDefinedWorkers, } from "../../connector-worker-sdk.js";
21
21
  import { runInJobContext } from "../execContext.js";
22
22
  function joinRoot(root, p) {
@@ -121,6 +121,24 @@ export function adaptConnectorHandler(worker) {
121
121
  return isRecord(ret) ? ret : {};
122
122
  };
123
123
  }
124
+ /**
125
+ * Validate a connector worker's job lock timeout (issue #596) before it reaches the
126
+ * engine. Unlike a manifest `workers[].timeoutMs` (author-time validated by
127
+ * `collectManifestIssues`) or a `w.run({ timeoutMs })` (validated at flow build), a
128
+ * connector timeout arrives from a THIRD-PARTY pack — `defineWorker({ timeoutMs })`
129
+ * in pack code or the `timeoutMs` field of its `nano-ide.ext.json` — with no
130
+ * validating gate in between. A zero/negative lock would expire instantly (the job
131
+ * re-activated mid-handler ⇒ duplicate execution) and a non-integer is a pack typo;
132
+ * fail closed at registration, naming the source, rather than propagate either to
133
+ * the engine.
134
+ */
135
+ function validateConnectorTimeout(value, source, jobType, packId) {
136
+ if (!Number.isInteger(value) || value <= 0) {
137
+ throw new Error(`connector worker "${jobType}" (pack "${packId}"): ${source} timeoutMs must be a ` +
138
+ `positive integer (ms), got ${JSON.stringify(value)}`);
139
+ }
140
+ return value;
141
+ }
124
142
  /**
125
143
  * Mount every enabled connector worker (`workers[]` entries carrying a
126
144
  * `connector` field). Fails closed on a seam mismatch (an enabled connector whose
@@ -192,11 +210,24 @@ export async function mountConnectors(ctx, app) {
192
210
  }
193
211
  const inner = adaptConnectorHandler(worker);
194
212
  const wrapped = (job) => runInJobContext({ instanceKey: job.processInstanceKey, elementId: job.elementId, jobType }, () => inner(job));
213
+ // Job lock timeout (issue #596) precedence, first declared wins:
214
+ // 1. the pack's `defineWorker({ timeoutMs })` — the authoritative runtime value
215
+ // 2. the pack's `nano-ide.ext.json` spec — the pack's design-time default
216
+ // 3. the app manifest's `workers[].timeoutMs` — the app author's declaration
217
+ // (mirrors the maxParallelJobs precedence below). The manifest value is already
218
+ // author-time validated (`collectManifestIssues`); the two pack-supplied values
219
+ // are validated here before either reaches the engine as a lock horizon.
220
+ const timeoutMs = worker.timeoutMs !== undefined
221
+ ? validateConnectorTimeout(worker.timeoutMs, "defineWorker", jobType, packId)
222
+ : spec.timeoutMs !== undefined
223
+ ? validateConnectorTimeout(spec.timeoutMs, "nano-ide.ext.json", jobType, packId)
224
+ : workerTimeoutMs(decl);
195
225
  const sub = await ctx.engine.registerWorker(jobType, wrapped, {
196
226
  workerName: `${ctx.manifest.id}:${jobType}`,
197
227
  // The pack's `defineWorker({ maxParallelJobs })` is the authoritative runtime
198
228
  // value; the ext.json spec is a design-time default when the code omits it.
199
229
  maxParallelJobs: worker.maxParallelJobs ?? spec.maxParallelJobs,
230
+ timeoutMs,
200
231
  });
201
232
  subs.push(sub);
202
233
  jobTypes.push(jobType);
@@ -2,7 +2,7 @@
2
2
  // on the engine. Handlers are resolved by a small, documented contract and are injected
3
3
  // with the app's runtime API (datasource + engine + host utils).
4
4
  import { isRecord } from "../guards.js";
5
- import { workerJobType } from "../manifest.js";
5
+ import { workerJobType, workerTimeoutMs } from "../manifest.js";
6
6
  import { runLlmJob } from "./llm.js";
7
7
  import { runInJobContext } from "../execContext.js";
8
8
  import { readLineage } from "../lineage.js";
@@ -274,6 +274,8 @@ export async function mountWorkers(ctx, app, sched = defaultScheduler()) {
274
274
  };
275
275
  const sub = await ctx.engine.registerWorker(jobType, wrapped, {
276
276
  workerName: `${ctx.manifest.id}:${jobType}`,
277
+ // The declared job lock timeout (issue #596) — absent ⇒ the engine/SDK default.
278
+ timeoutMs: workerTimeoutMs(decl),
277
279
  });
278
280
  subs.push(sub);
279
281
  jobTypes.push(jobType);
@@ -293,6 +295,8 @@ export async function mountWorkers(ctx, app, sched = defaultScheduler()) {
293
295
  };
294
296
  const sub = await ctx.engine.registerWorker(jobType, wrapped, {
295
297
  workerName: `${ctx.manifest.id}:${jobType}`,
298
+ // The declared job lock timeout (issue #596) — absent ⇒ the engine/SDK default.
299
+ timeoutMs: workerTimeoutMs(decl),
296
300
  });
297
301
  subs.push(sub);
298
302
  jobTypes.push(jobType);
@@ -125,6 +125,18 @@ export function collectManifestIssues(m) {
125
125
  });
126
126
  }
127
127
  }
128
+ // The pending-schema job lock timeout (issue #596): when present it must be a
129
+ // positive integer of ms — a zero/negative lock would expire instantly (the job
130
+ // re-activated mid-handler), and a non-integer is a manifest typo to fail fast on.
131
+ if (worker !== undefined && "timeoutMs" in worker) {
132
+ const t = worker.timeoutMs;
133
+ if (typeof t !== "number" || !Number.isInteger(t) || t <= 0) {
134
+ issues.push({
135
+ path: `workers[${i}].timeoutMs`,
136
+ message: "timeoutMs must be a positive integer (ms)",
137
+ });
138
+ }
139
+ }
128
140
  });
129
141
  }
130
142
  const data = isRecord(obj.data) ? obj.data : undefined;
@@ -286,6 +286,7 @@ export declare class SdkEngineClient implements EngineClient {
286
286
  registerWorker(jobType: string, handler: JobHandler, options?: {
287
287
  workerName?: string;
288
288
  maxParallelJobs?: number;
289
+ timeoutMs?: number;
289
290
  fetchVariables?: string[];
290
291
  }): Promise<WorkerSubscription>;
291
292
  /** Stop one worker, tolerating a Falcon worker whose transport never bound
@@ -1074,6 +1074,9 @@ export class SdkEngineClient {
1074
1074
  jobType,
1075
1075
  workerName: options?.workerName ?? `urban:${jobType}`,
1076
1076
  maxParallelJobs: options?.maxParallelJobs ?? 8,
1077
+ // The job lock timeout (issue #596): pass it through only when declared, so an
1078
+ // undeclared worker keeps the SDK's default lock rather than an explicit value.
1079
+ ...(options?.timeoutMs !== undefined ? { jobTimeoutMs: options.timeoutMs } : {}),
1077
1080
  fetchVariables: options?.fetchVariables,
1078
1081
  jobHandler: async (job) => {
1079
1082
  const rawKey = job.jobKey;
@@ -4,11 +4,11 @@ export { EventBus } from "./core/events.ts";
4
4
  export type { DispatchMode, Disposer, EmitChannel, ErrorSink, EventBusOptions, Listener, Middleware, ParallelChannel, SerialChannel, WaterfallChannel, } from "./core/events.ts";
5
5
  export { URBAN_EVENT_MODES, createUrbanEvents, mountExtensions, urbanEventMode } from "./core/extensions.ts";
6
6
  export type { DispatchRequest, DispatchResponse, ExtensionHost, ExtensionRegistered, ExtensionSetupContext, GateDecision, GateRequest, LifecycleEvent, MountExtensionsOptions, ReconcileEvent, UrbanEventName, UrbanEvents, UrbanExtension, } from "./core/extensions.ts";
7
- export { bindModeToHost, expandEnv, expandEnvString, isBindMode, loadManifest, parseManifest, resolveBindHost, resolveBindMode, workerJobType, ALL_INTERFACES_HOST, BIND_ENV_VAR, LOOPBACK_HOST, } from "./core/manifest.ts";
8
- export type { ActionDecl, AppManifest, BindMode, ChatSurface, DataSource, DomainField, DomainType, InstanceTracking, LlmBinding, NetworkConfig, PagesSurface, Surfaces, TaskInboxSurface, Trigger, Worker, } from "./core/manifest.ts";
7
+ export { bindModeToHost, expandEnv, expandEnvString, isBindMode, loadManifest, parseManifest, resolveBindHost, resolveBindMode, workerJobType, workerTimeoutMs, ALL_INTERFACES_HOST, BIND_ENV_VAR, LOOPBACK_HOST, } from "./core/manifest.ts";
8
+ export type { ActionDecl, AppManifest, BindMode, ChatSurface, DataSource, DomainField, DomainType, InstanceTracking, LlmBinding, NetworkConfig, PagesSurface, Surfaces, TaskInboxSurface, Trigger, Worker, WorkerDecl, } from "./core/manifest.ts";
9
9
  export { collectManifestIssues, ManifestValidationError, validateManifest, } from "./core/validate.ts";
10
10
  export type { ValidationIssue } from "./core/validate.ts";
11
- export type { EngineClient, AgentHistoryFilter, AgentHistoryRecord, AgentInstanceFilter, AgentInstanceMetrics, AgentInstanceSummary, ElementInstanceState, ElementInstanceSummary, ElementInstanceFilter, ElementInstanceWaitState, ElementInstanceWaitStateFilter, WaitStateType, EngineJob, FormSchema, HostContext, HttpHandler, HttpRequest, HttpResponse, HttpServer, IncidentState, EngineIncidentState, IncidentFilter, IncidentSummary, JobFilter, JobHandler, JobSummary, CreatedProcessInstance, ProcessDefinitionIdentity, ProcessInstanceSnapshot, ProcessInstanceState, SqliteDb, UserTaskState, UserTaskSummary, UserTaskFilter, VariableFilter, VariableSummary, WatchHandle, WorkerSubscription, } from "./core/host.ts";
11
+ export type { EngineClient, AgentHistoryFilter, AgentHistoryRecord, AgentInstanceFilter, AgentInstanceMetrics, AgentInstanceSummary, ElementInstanceState, ElementInstanceSummary, ElementInstanceFilter, ElementInstanceWaitState, ElementInstanceWaitStateFilter, WaitStateType, EngineJob, FormSchema, HostContext, HttpHandler, HttpRequest, HttpResponse, HttpServer, IncidentState, EngineIncidentState, IncidentFilter, IncidentSummary, JobFilter, JobHandler, JobSummary, CreatedProcessInstance, ProcessDefinitionIdentity, ProcessInstanceSnapshot, ProcessInstanceState, RegisterWorkerOptions, SqliteDb, UserTaskState, UserTaskSummary, UserTaskFilter, VariableFilter, VariableSummary, WatchHandle, WorkerSubscription, } from "./core/host.ts";
12
12
  export type { TranscriptContentBlock, TranscriptContentType, TranscriptToolCall, TranscriptTurnMetrics, TranscriptTurnRole, } from "@nanobpm/agentic/transcript";
13
13
  export { buildFormSchema, parseFormSchema, pickFormLinkage, presentFormIdentifier, resolveFormIdentifier, } from "./core/form-contract.ts";
14
14
  export { pickProcessDefinitionIdentity, presentEngineKey, presentString, } from "./core/process-identity.ts";
@@ -5,7 +5,7 @@ export { createUrbanApp } from "./core/runtime.js";
5
5
  export { EventBus } from "./core/events.js";
6
6
  export { URBAN_EVENT_MODES, createUrbanEvents, mountExtensions, urbanEventMode } from "./core/extensions.js";
7
7
  // Manifest
8
- export { bindModeToHost, expandEnv, expandEnvString, isBindMode, loadManifest, parseManifest, resolveBindHost, resolveBindMode, workerJobType, ALL_INTERFACES_HOST, BIND_ENV_VAR, LOOPBACK_HOST, } from "./core/manifest.js";
8
+ export { bindModeToHost, expandEnv, expandEnvString, isBindMode, loadManifest, parseManifest, resolveBindHost, resolveBindMode, workerJobType, workerTimeoutMs, ALL_INTERFACES_HOST, BIND_ENV_VAR, LOOPBACK_HOST, } from "./core/manifest.js";
9
9
  // Validation
10
10
  export { collectManifestIssues, ManifestValidationError, validateManifest, } from "./core/validate.js";
11
11
  // Shared form/user-task contract normalization (issue #252): the single source of truth
@@ -48,6 +48,16 @@ export interface GenResult {
48
48
  incomplete: boolean;
49
49
  /** Per-file model-derivation errors (empty on success). */
50
50
  modelErrors: ModelError[];
51
+ /** Job types of inline-handled (`w.run`) code-first steps — the set the app's in-process
52
+ * Worker already serves (nano-ide#595). The worker-stub scaffolder skips these; empty for a
53
+ * model-first app. */
54
+ inlineTaskTypes: string[];
55
+ /** The code-first models derived in-memory this run (`deriveModels().models`) — the
56
+ * worker-stub scaffolder plans against these in addition to the on-disk models, since a
57
+ * declared `models` block (e.g. `models.workflows`) suppresses the `resources/` convention
58
+ * scan that would otherwise pick the written `.bpmn` up (nano-ide#595). Empty for a
59
+ * model-first app. */
60
+ derivedModels: ModelSource[];
51
61
  /** Non-fatal spec-hygiene warnings (e.g. a requestBody schema shared by >1 operation). Empty on
52
62
  * a clean spec. Surfaced by the CLI but never fail gen/check — advisory only. */
53
63
  warnings: string[];
@@ -257,7 +257,7 @@ export async function runGen(opts) {
257
257
  swept.push(rel);
258
258
  }
259
259
  }
260
- return { artifacts, drift, swept: swept.sort(), incomplete: derived.incomplete, modelErrors: derived.errors, warnings };
260
+ return { artifacts, drift, swept: swept.sort(), incomplete: derived.incomplete, modelErrors: derived.errors, inlineTaskTypes: derived.inlineTaskTypes, derivedModels: derived.models, warnings };
261
261
  }
262
262
  export { dirOf, join as joinPath };
263
263
  /** Derive code-first models in-memory (no writes) — backs `urban derive --stdout`, the
@@ -30,7 +30,15 @@ export async function generate(opts) {
30
30
  return empty;
31
31
  const write = !opts.check;
32
32
  const scaffoldOpts = { root: opts.root, io: opts.io, manifestFile: opts.manifestFile, write };
33
- const workers = await scaffoldWorkers(scaffoldOpts);
33
+ // Inline-handled (`w.run`) steps are already served by the app's in-process Worker — never
34
+ // scaffold a competing throwing stub for them (nano-ide#595). The derived models are also
35
+ // handed over: a code-first manifest's declared `models` block suppresses the resources/
36
+ // convention scan in readModels, so without them the scaffolder would plan from nothing.
37
+ const workers = await scaffoldWorkers({
38
+ ...scaffoldOpts,
39
+ inlineTaskTypes: res.inlineTaskTypes,
40
+ extraModels: res.derivedModels,
41
+ });
34
42
  const operations = await scaffoldOperations(scaffoldOpts);
35
43
  const missingStubs = [
36
44
  ...workers.outcomes.filter((o) => o.status === "would-create").map((o) => o.handlerPath),
@@ -38,6 +38,13 @@ export interface DerivedModels {
38
38
  models: ModelSource[];
39
39
  /** Derived flow ids (used for the provenance-scoped stale sweep). */
40
40
  ids: string[];
41
+ /** Job types of inline-handled (`w.run`) steps across every derived declarative flow —
42
+ * the set the app's in-process Worker already serves (nano-ide#595). The worker-stub
43
+ * scaffolder skips these; only `w.task` (external) steps may be scaffolded. Empty when
44
+ * derivation was a no-op (no loader / no workflow files) or all flows are imperative
45
+ * (an imperative flow's steps run inside its single `:__orchestrate` job, which the
46
+ * planner already skips). */
47
+ inlineTaskTypes: string[];
41
48
  /** Per-flow `{ id, kind, xml }` for the non-writing preview (`urban derive --stdout`). */
42
49
  list: DerivedModelInfo[];
43
50
  /** The output directory the artifacts were written into. */
@@ -8,7 +8,7 @@
8
8
  // optional `GenIO.importModule` (present on Node with type-stripping, and on Deno). When the
9
9
  // loader is absent — or the app authors its models directly (model-first) — derivation is a
10
10
  // no-op and the rest of `urban gen` proceeds on the authored/derived models unchanged.
11
- import { toDeployableBpmn } from "@nanobpm/workflow";
11
+ import { inlineJobTypes, toDeployableBpmn } from "@nanobpm/workflow";
12
12
  import { expandPattern, joinPath } from "./gen.js";
13
13
  import { isRecord } from "../runtime/core/guards.js";
14
14
  /** Default source glob for code-first flows (matches the code-first scaffold layout). */
@@ -54,6 +54,7 @@ function emptyDerived(outDir) {
54
54
  artifacts: [],
55
55
  models: [],
56
56
  ids: [],
57
+ inlineTaskTypes: [],
57
58
  list: [],
58
59
  outDir,
59
60
  attempted: false,
@@ -131,6 +132,8 @@ export async function deriveModels(root, io, manifest) {
131
132
  const path = `${outDir}/${bpmnFilename(id)}`;
132
133
  out.artifacts.push({ path, content: xml });
133
134
  out.models.push({ path, xml });
135
+ if (value.kind === "declarative")
136
+ out.inlineTaskTypes.push(...inlineJobTypes(value));
134
137
  out.list.push({ id, kind: value.kind, xml });
135
138
  out.ids.push(id);
136
139
  }
@@ -26,7 +26,7 @@ export interface WorkerStubPlan {
26
26
  stub: string;
27
27
  manifestEntry: StubManifestEntry;
28
28
  }
29
- export type SkipReason = "already-wired" | "orchestrator" | "duplicate" | "external";
29
+ export type SkipReason = "already-wired" | "orchestrator" | "duplicate" | "external" | "inline";
30
30
  export interface SkippedWorker {
31
31
  taskType: string;
32
32
  reason: SkipReason;
@@ -42,9 +42,12 @@ export declare function renderWorkerStub(taskType: string, typedIn: boolean, typ
42
42
  /**
43
43
  * Plan write-once handler stubs from the models. A stub is planned for each service-task
44
44
  * `taskType` that is NOT already wired in the manifest, NOT the imperative orchestrator, NOT
45
- * declared external (serviced by an out-of-process worker), and not a duplicate of one already
46
- * planned. `declaredTypeIds` are the manifest `types` ids — an envelope `in`/`out` is typed only
47
- * when it names one (matching the worker-io deriver). `externalTaskTypes` are the manifest's
48
- * declared external task types, which the app owns the model for but deliberately does not host.
45
+ * declared external (serviced by an out-of-process worker), NOT inline-handled (a code-first
46
+ * `w.run` step whose handler the app's in-process Worker already serves — nano-ide#595), and
47
+ * not a duplicate of one already planned. `declaredTypeIds` are the manifest `types` ids — an
48
+ * envelope `in`/`out` is typed only when it names one (matching the worker-io deriver).
49
+ * `externalTaskTypes` are the manifest's declared external task types, which the app owns the
50
+ * model for but deliberately does not host. `inlineTaskTypes` are the flow-derived inline
51
+ * (`w.run`) job types (`deriveModels().inlineTaskTypes`).
49
52
  */
50
- export declare function planWorkerScaffold(models: ModelSource[], workers?: ScaffoldWorker[], declaredTypeIds?: Iterable<string>, externalTaskTypes?: Iterable<string>): WorkerScaffoldPlan;
53
+ export declare function planWorkerScaffold(models: ModelSource[], workers?: ScaffoldWorker[], declaredTypeIds?: Iterable<string>, externalTaskTypes?: Iterable<string>, inlineTaskTypes?: Iterable<string>): WorkerScaffoldPlan;
@@ -65,17 +65,21 @@ export function renderWorkerStub(taskType, typedIn, typedOut) {
65
65
  /**
66
66
  * Plan write-once handler stubs from the models. A stub is planned for each service-task
67
67
  * `taskType` that is NOT already wired in the manifest, NOT the imperative orchestrator, NOT
68
- * declared external (serviced by an out-of-process worker), and not a duplicate of one already
69
- * planned. `declaredTypeIds` are the manifest `types` ids — an envelope `in`/`out` is typed only
70
- * when it names one (matching the worker-io deriver). `externalTaskTypes` are the manifest's
71
- * declared external task types, which the app owns the model for but deliberately does not host.
68
+ * declared external (serviced by an out-of-process worker), NOT inline-handled (a code-first
69
+ * `w.run` step whose handler the app's in-process Worker already serves — nano-ide#595), and
70
+ * not a duplicate of one already planned. `declaredTypeIds` are the manifest `types` ids — an
71
+ * envelope `in`/`out` is typed only when it names one (matching the worker-io deriver).
72
+ * `externalTaskTypes` are the manifest's declared external task types, which the app owns the
73
+ * model for but deliberately does not host. `inlineTaskTypes` are the flow-derived inline
74
+ * (`w.run`) job types (`deriveModels().inlineTaskTypes`).
72
75
  */
73
- export function planWorkerScaffold(models, workers = [], declaredTypeIds = [], externalTaskTypes = []) {
76
+ export function planWorkerScaffold(models, workers = [], declaredTypeIds = [], externalTaskTypes = [], inlineTaskTypes = []) {
74
77
  const wired = new Set(workers
75
78
  .map((w) => w?.taskType)
76
79
  .filter((t) => typeof t === "string" && t.length > 0));
77
80
  const declared = new Set(declaredTypeIds);
78
81
  const external = new Set(externalTaskTypes);
82
+ const inline = new Set(inlineTaskTypes);
79
83
  const plans = [];
80
84
  const skipped = [];
81
85
  const seenTaskTypes = new Set();
@@ -91,6 +95,10 @@ export function planWorkerScaffold(models, workers = [], declaredTypeIds = [], e
91
95
  skipped.push({ taskType, reason: "external" });
92
96
  continue;
93
97
  }
98
+ if (inline.has(taskType)) {
99
+ skipped.push({ taskType, reason: "inline" });
100
+ continue;
101
+ }
94
102
  if (wired.has(taskType)) {
95
103
  skipped.push({ taskType, reason: "already-wired" });
96
104
  continue;
@@ -1,4 +1,5 @@
1
1
  import type { GenIO } from "./gen.ts";
2
+ import type { ModelSource } from "./derivers/worker-io.ts";
2
3
  import { type SkippedWorker, type StubManifestEntry } from "./scaffold/workers.ts";
3
4
  /**
4
5
  * Detect the indentation of a JSON document from its first indented line, so a rewrite can
@@ -18,6 +19,22 @@ export interface ScaffoldOptions {
18
19
  manifestFile?: string;
19
20
  /** Apply changes (create files + patch manifest). Default false = dry-run. */
20
21
  write?: boolean;
22
+ /**
23
+ * Job types of inline-handled (`w.run`) code-first steps — the set the app's in-process
24
+ * Worker already serves (nano-ide#595). The planner skips these with reason `"inline"` so
25
+ * `urban gen` never scaffolds a throwing stub that competes with the real handler. Pass
26
+ * `deriveModels().inlineTaskTypes` (the `generate` composition does).
27
+ */
28
+ inlineTaskTypes?: Iterable<string>;
29
+ /**
30
+ * Extra in-memory models to plan against in addition to the on-disk ones `readModels`
31
+ * resolves (nano-ide#595). A code-first app's derived `.bpmn` lives under
32
+ * `resources/processes/`, which `readModels` does NOT resolve when the manifest declares a
33
+ * `models` block (e.g. `models.workflows`) without `models.processes` — a declared block
34
+ * suppresses the `resources/` convention. Pass `deriveModels().models` so the scaffolder
35
+ * plans from the same fused model set the type-contract derivers saw.
36
+ */
37
+ extraModels?: ModelSource[];
21
38
  }
22
39
  export type StubStatus = "created" | "would-create" | "kept";
23
40
  export interface StubOutcome {
@@ -38,9 +38,16 @@ export async function scaffoldWorkers(opts) {
38
38
  // Preserve the manifest's own indentation when we patch it back (default tab, matching the
39
39
  // scaffold's Biome config), so wiring a worker never reformats the file out from under lint.
40
40
  const manifestIndent = detectJsonIndent(manifestRaw);
41
- const models = await readModels(root, io, manifest);
41
+ const diskModels = await readModels(root, io, manifest);
42
42
  const declaredTypeIds = Object.keys(manifest.types ?? {});
43
- const { plans, skipped } = planWorkerScaffold(models, manifest.workers ?? [], declaredTypeIds, manifest.externalTaskTypes ?? []);
43
+ // Fuse on-disk models with any in-memory extras (code-first derived models — see
44
+ // `ScaffoldOptions.extraModels`), deduped by path with the IN-MEMORY model winning: a derived
45
+ // model whose path also exists on disk may be stale there (`--check`/`--no-models` never write
46
+ // it), so planning from the disk copy would miss newly added tasks and keep removed ones. This
47
+ // mirrors the precedence `collectAll` (gen.ts) gives the type-contract derivers.
48
+ const extraPaths = new Set((opts.extraModels ?? []).map((m) => m.path));
49
+ const models = [...diskModels.filter((m) => !extraPaths.has(m.path)), ...(opts.extraModels ?? [])];
50
+ const { plans, skipped } = planWorkerScaffold(models, manifest.workers ?? [], declaredTypeIds, manifest.externalTaskTypes ?? [], opts.inlineTaskTypes ?? []);
44
51
  const outcomes = [];
45
52
  const wired = [];
46
53
  for (const plan of plans) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nanobpm/urban",
3
- "version": "0.96.2",
3
+ "version": "0.97.0",
4
4
  "description": "Urban: build and run code-first apps on Nano — runtime, derivation toolkit, and CLI in one. Author durable processes with @nanobpm/workflow (defineFlow), a typed datasource, forms, triggers and surfaces from a nano.app.json manifest, on Node or Deno.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -106,9 +106,9 @@
106
106
  "@nanobpm/agentic": "^0.15.0",
107
107
  "@nanobpm/nano-app-schema": "^0.11.0",
108
108
  "@nanobpm/nano-sdk": "^1.2.5",
109
- "@nanobpm/workflow": "^0.15.0",
109
+ "@nanobpm/workflow": "^0.16.0",
110
110
  "bpmn-auto-layout": "^2.0.0-alpha.2",
111
- "create-urban-app": "^0.15.2",
111
+ "create-urban-app": "^0.15.3",
112
112
  "yaml": "^2.9.0"
113
113
  },
114
114
  "devDependencies": {
package/src/index.ts CHANGED
@@ -31,6 +31,7 @@ export {
31
31
  declarativeToBpmn,
32
32
  declarativeToLayoutedBpmn,
33
33
  externalJobTypes,
34
+ inlineJobTypes,
34
35
  envelope,
35
36
  layoutBpmn,
36
37
  toBpmn,
@@ -20,6 +20,15 @@ test("defineWorker records handlers that drainDefinedWorkers returns then clears
20
20
  assert.deepEqual(drainDefinedWorkers(), []);
21
21
  });
22
22
 
23
+ test("defineWorker carries the declared job lock timeout (timeoutMs) through the drain (issue #596)", () => {
24
+ drainDefinedWorkers(); // start clean
25
+ defineWorker({ type: "a:slow", timeoutMs: 900_000, handle: async () => ({}) });
26
+ defineWorker({ type: "a:fast", handle: async () => ({}) });
27
+ const [slow, fast] = drainDefinedWorkers();
28
+ assert.equal(slow.timeoutMs, 900_000);
29
+ assert.equal(fast.timeoutMs, undefined);
30
+ });
31
+
23
32
  test("defineWorker rejects a missing type or non-function handle", () => {
24
33
  assert.throws(() => defineWorker({ type: "", handle: async () => ({}) }), /type` is required/);
25
34
  const missingHandle: Parameters<typeof defineWorker>[0] = JSON.parse('{"type":"x"}');
@@ -49,6 +49,8 @@ export interface ConnectorWorkerOptions {
49
49
  export interface DefinedConnectorWorker {
50
50
  type: string;
51
51
  maxParallelJobs?: number;
52
+ /** Job lock timeout, ms (issue #596) — carried from `defineWorker({ timeoutMs })`. */
53
+ timeoutMs?: number;
52
54
  handle: ConnectorWorkerOptions["handle"];
53
55
  }
54
56
 
@@ -66,7 +68,12 @@ export function defineWorker(opts: ConnectorWorkerOptions): void {
66
68
  if (typeof opts.handle !== "function") {
67
69
  throw new Error(`defineWorker("${opts.type}"): handle must be a function`);
68
70
  }
69
- registered.push({ type: opts.type, maxParallelJobs: opts.maxParallelJobs, handle: opts.handle });
71
+ registered.push({
72
+ type: opts.type,
73
+ maxParallelJobs: opts.maxParallelJobs,
74
+ timeoutMs: opts.timeoutMs,
75
+ handle: opts.handle,
76
+ });
70
77
  }
71
78
 
72
79
  /** Return every worker registered since the last drain, and clear the registry.