@grida/fx 0.1.0-alpha.2 → 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -5,10 +5,10 @@ files and to plan, price and run them. Grida FX is a workflow engine for generat
5
5
  pipelines: write a workflow file, and FX plans it, prices it before anything is spent, caches
6
6
  every paid call by its request, and records the run. It works with your own provider keys.
7
7
 
8
- This is a **preview** (`0.x` pre-releases under the npm tag `next`).
8
+ Stable releases start at `0.1.0` and use npm's default `latest` tag. Prereleases use `next`.
9
9
 
10
10
  ```sh
11
- npm install @grida/fx@next # or: npm install -g @grida/fx@next
11
+ npm install @grida/fx # or: npm install -g @grida/fx
12
12
  npx grida-fx --help
13
13
  ```
14
14
 
@@ -22,16 +22,22 @@ your machine:
22
22
  | Linux on x64, glibc 2.28 or later | `@grida/fx-linux-x64-gnu` |
23
23
  | Linux on arm64, glibc 2.28 or later | `@grida/fx-linux-arm64-gnu` |
24
24
 
25
- **Windows is not in the preview**: the engine's runner uses Unix process groups and signals. Use
25
+ **Native Windows is not supported yet**: the engine's runner uses Unix process groups and signals. Use
26
26
  WSL 2, which runs the Linux packages. Linux with musl (Alpine) is not supported either. Node 18 or
27
27
  later.
28
28
 
29
+ FX is also the `fx` verb of the npm `grida` command: a `grida` release that pins this package
30
+ runs its engine as `grida fx <verb>`. For that host this package exports
31
+ its launcher as `@grida/fx/cli` (`launch`, `HOST_CONTRACT`); see
32
+ [spec/distribution.md](https://github.com/gridaco/fx/blob/main/spec/distribution.md). The SDK
33
+ stays `import … from "@grida/fx"`.
34
+
29
35
  `grida-fx` reports what is missing when it finds no engine. If you install with
30
36
  `--omit=optional`, or need a binary of your own, set `GRIDA_FX_BIN` to the path of a `grida-fx`
31
37
  binary: the command and the SDK use it first.
32
38
 
33
- Some steps run on Python in the preview (your own Python nodes, and the built-in local types such
34
- as `image.resize`): those projects also need `pip install --pre grida`, or `GRIDA_FX_PYTHON`
39
+ Some steps run on Python (your own Python nodes, and the built-in local types such
40
+ as `image.resize`): those projects also need `pip install grida`, or `GRIDA_FX_PYTHON`
35
41
  pointing at a Python that has them. A project whose steps are all paid built-ins and `select`
36
42
  needs only this package. See [Getting started](https://github.com/gridaco/fx/blob/main/docs/guide/01-getting-started.md).
37
43
 
@@ -58,14 +64,43 @@ const icon = result.outputs.icon; // a RunFile: digest, kind, path, read()
58
64
  runs, and reads the run back: `ok`, `incomplete`, `chargedUsd`, `failed`, `outputs`, `steps`.
59
65
  A failed step does not reject.
60
66
  - `project(runDir)` and `inspect(runOrWorkflowId, { verify })`: a run's record and summary.
67
+ - `loadRun(target, { verify })`: a `RunRecord` with a pinned absolute `runDir` and
68
+ engine `inspection`. Its `snapshot()`, `events({ after, limit })` and async
69
+ `follow({ after, pollIntervalMs, signal })` methods use the same public reader as
70
+ the CLI. Following yields nonempty bounded batches until broken or aborted,
71
+ including across resumes. It owns no execution process or exit code.
72
+ - `inspectControl(run)` and `cancel(run, { invocation, wait, timeout })`: exact-target local
73
+ control, independent of viewer/service lifetime. Results keep their `lower_snake_case` wire
74
+ fields; structured failures raise `RunControlError` with `code` and `result`.
75
+ - `listRuns({ workflow })`: the project's runs, newest first, each with its `folder`, a `runDir`
76
+ resolved against `cwd`, and `lower_snake_case` wire fields (`state`, `placement`,
77
+ `charged_usd`, …). `removeRuns(runs, { preview })`: removes exactly the runs given (filter
78
+ `listRuns` yourself); `preview: true` removes nothing. A refused or partial run is an entry's
79
+ `outcome`, not a rejection; a RUN that is not a run raises `RunRemovalError` with `code` and
80
+ `run`, before anything is removed.
61
81
  - `binary()` and `engineVersion()`: the engine in use.
62
82
 
63
83
  A target is a workflow file, a workflow id, or a builder `file.py:function`. Options:
64
84
  `inputs` (values), `inputFiles`, `routes`, `args` (a builder's arguments), `maxUsd`, `cwd`,
65
85
  `env` (for example `GRIDA_FX_PYTHON`) and `signal` (an `AbortSignal`); `run` also takes `live`,
66
- `yesUpTo`, `runDir` and `deliver`. Relative paths start at `cwd`. The engine's errors reject with
86
+ `yesUpTo`, `deliver`, and one of `name` (create-only), `resume` (require-existing),
87
+ or `runDir` (explicit-folder create/resume). Relative paths start at `cwd`. The engine's errors reject with
67
88
  `FxError`, which carries its `exitCode` and `stderr`.
68
89
 
90
+ Aborting a `run` requests graceful cancellation once with SIGTERM and waits for engine cleanup
91
+ before rejecting. There is no automatic runner force timer; stuck cleanup can keep the promise
92
+ pending. Aborting only a control waiter ends that wait without retracting accepted cancellation.
93
+ See [Stopping and continuing a run](../../docs/guide/08-run-control.md) for guarded requests,
94
+ wait timeouts, local completion and unknown remote outcomes. These APIs describe current source;
95
+ check your installed version for availability.
96
+
97
+ Observation abort stops only its reader. Apply an entire batch before checkpointing
98
+ its opaque cursor; `RunObservationError` keeps a reader's `code` and `document`.
99
+ Inspection and a later snapshot are independent samples. See
100
+ [Working with runs from an SDK](../../docs/guide/09-sdk-runs.md) for saved/named
101
+ records and observing another process. SDK execution still suppresses viewer
102
+ hosting and returns after completion.
103
+
69
104
  ## Writing workflows
70
105
 
71
106
  ```ts
package/dist/api.d.ts CHANGED
@@ -90,6 +90,8 @@ export declare class RunResult {
90
90
  readonly inspection: Inspection;
91
91
  constructor(runDir: string, exit: Exit, projection: Projection, inspection: Inspection);
92
92
  private get finished();
93
+ /** The initialized invocation represented by this result's projection. */
94
+ get invocationId(): string | null;
93
95
  /** Whether every step that had to run succeeded and the run ended normally. */
94
96
  get ok(): boolean;
95
97
  /** Whether the run stopped before everything ran (running it again continues it). */
package/dist/api.js CHANGED
@@ -165,6 +165,11 @@ export class RunResult {
165
165
  get finished() {
166
166
  return this.projection.run?.run_finished;
167
167
  }
168
+ /** The initialized invocation represented by this result's projection. */
169
+ get invocationId() {
170
+ const value = this.projection.run?.run_started?.invocation_id;
171
+ return typeof value === "string" ? value : null;
172
+ }
168
173
  /** Whether every step that had to run succeeded and the run ended normally. */
169
174
  get ok() {
170
175
  return this.finished?.ok === true;
@@ -234,7 +239,7 @@ export function decode(encoded, placed) {
234
239
  throw new FxError(`the run's record holds a value in no known form: ${JSON.stringify(encoded)}`);
235
240
  }
236
241
  /** The options `run` still takes with a {@link Plan}. */
237
- const RUN_ONLY = ["live", "yesUpTo", "runDir", "deliver", "signal"];
242
+ const RUN_ONLY = ["live", "yesUpTo", "runDir", "name", "resume", "deliver", "signal"];
238
243
  /**
239
244
  * Runs `target`, or a plan, after planning it: a plan with problems rejects with
240
245
  * {@link PlanRefused} before any folder exists. `live: true` admits paid calls, within a
@@ -261,7 +266,7 @@ export async function run(target, options = {}) {
261
266
  if (!planned.ok) {
262
267
  throw new PlanRefused(planned);
263
268
  }
264
- const done = await withInputsFile(request, (inputsFile) => call(["run", ...planningArgs(request, inputsFile), ...own], callOptions(request, signal)));
269
+ const done = await withInputsFile(request, (inputsFile) => call(["run", ...planningArgs(request, inputsFile), ...own, "--no-view"], callOptions(request, signal)));
265
270
  if (done.status === INTERRUPTED) {
266
271
  throw new FxError("the run was interrupted", {
267
272
  exitCode: done.status,
package/dist/cli.d.ts CHANGED
@@ -1,7 +1,13 @@
1
1
  /**
2
- * The `grida-fx` command that `@grida/fx` installs: it finds the engine (`binary.ts`) and runs it
3
- * with this process's arguments, standard streams and working directory, and ends as the engine
4
- * ended: with its exit status, or by the same signal.
2
+ * The command launcher: it finds the engine (`binary.ts`) and runs it with the given arguments,
3
+ * this process's standard streams and working directory, and ends as the engine ended: with its
4
+ * exit status, or by the same signal. `@grida/fx`'s own `grida-fx` command is {@link main}; a
5
+ * host command that carries FX as a verb of its own (the npm `grida` command's `grida fx`) calls
6
+ * {@link launch} through the `@grida/fx/cli` export (spec/distribution.md).
7
+ *
8
+ * The invoker. {@link launch} tells the engine which command started it (`GRIDA_FX_INVOKER`), so
9
+ * usage, the error prefix and the hints the engine prints name the command as its user types it:
10
+ * `grida-fx` or `grida fx`. This launcher's own messages use the same name.
5
11
  *
6
12
  * Signals. On Unix the engine runs in a process group (and session) of its own, so a signal meant
7
13
  * for the command reaches the engine exactly once, through this process: SIGINT, SIGTERM, SIGHUP
@@ -12,13 +18,34 @@
12
18
  * input, so it does not need the terminal's foreground group.
13
19
  */
14
20
  import { type ChildProcess } from "node:child_process";
21
+ /**
22
+ * The version of the contract between `@grida/fx/cli` and a host command: {@link launch}'s
23
+ * signature and behaviour, the invokers it accepts, and what the engine does with each. A host
24
+ * pins `@grida/fx` exactly and refuses a contract it was not written for.
25
+ */
26
+ export declare const HOST_CONTRACT = 1;
27
+ /** The environment variable that tells the engine which command started it. */
28
+ export declare const INVOKER_VARIABLE = "GRIDA_FX_INVOKER";
29
+ /** A command that launches the engine from JavaScript: `@grida/fx`'s `grida-fx`, or `grida`'s
30
+ * `grida fx`. (`python -m grida.fx` is the Python distribution's.) */
31
+ export type Invoker = "grida-fx" | "grida";
32
+ /** The command each invoker's user types, without the verb. */
33
+ export declare const COMMANDS: Readonly<Record<Invoker, string>>;
34
+ /** Options of {@link launch}. */
35
+ export interface LaunchOptions {
36
+ /** The command that started the engine (default: `grida-fx`). */
37
+ readonly invoker?: Invoker;
38
+ }
15
39
  /** Signals passed on to the engine. */
16
40
  export declare const FORWARDED: readonly ["SIGINT", "SIGTERM", "SIGHUP", "SIGQUIT"];
17
41
  /** The same signal again within this many milliseconds is a repeat of one interruption. */
18
42
  export declare const REPEAT_MS = 250;
19
- /** Runs the engine with `argv` (the arguments after the command's name) and ends this process as
20
- * the engine ended. */
43
+ /** `@grida/fx`'s `grida-fx` command: {@link launch} as the `grida-fx` invoker. */
21
44
  export declare function main(argv: readonly string[]): void;
45
+ /** Runs the engine with `argv` (the arguments after the command's name, and after `fx` for
46
+ * `grida fx`) and ends this process as the engine ended. Throws a `TypeError`, before anything
47
+ * runs, for an invoker this contract does not know. */
48
+ export declare function launch(argv: readonly string[], options?: LaunchOptions): void;
22
49
  /** Passes signals on to `child` (module comment); `remove` stops. */
23
50
  export declare function forwardSignals(child: ChildProcess, unix: boolean): {
24
51
  remove(): void;
package/dist/cli.js CHANGED
@@ -1,7 +1,13 @@
1
1
  /**
2
- * The `grida-fx` command that `@grida/fx` installs: it finds the engine (`binary.ts`) and runs it
3
- * with this process's arguments, standard streams and working directory, and ends as the engine
4
- * ended: with its exit status, or by the same signal.
2
+ * The command launcher: it finds the engine (`binary.ts`) and runs it with the given arguments,
3
+ * this process's standard streams and working directory, and ends as the engine ended: with its
4
+ * exit status, or by the same signal. `@grida/fx`'s own `grida-fx` command is {@link main}; a
5
+ * host command that carries FX as a verb of its own (the npm `grida` command's `grida fx`) calls
6
+ * {@link launch} through the `@grida/fx/cli` export (spec/distribution.md).
7
+ *
8
+ * The invoker. {@link launch} tells the engine which command started it (`GRIDA_FX_INVOKER`), so
9
+ * usage, the error prefix and the hints the engine prints name the command as its user types it:
10
+ * `grida-fx` or `grida fx`. This launcher's own messages use the same name.
5
11
  *
6
12
  * Signals. On Unix the engine runs in a process group (and session) of its own, so a signal meant
7
13
  * for the command reaches the engine exactly once, through this process: SIGINT, SIGTERM, SIGHUP
@@ -14,29 +20,54 @@
14
20
  import { spawn } from "node:child_process";
15
21
  import { constants } from "node:os";
16
22
  import { binary } from "./binary.js";
23
+ /**
24
+ * The version of the contract between `@grida/fx/cli` and a host command: {@link launch}'s
25
+ * signature and behaviour, the invokers it accepts, and what the engine does with each. A host
26
+ * pins `@grida/fx` exactly and refuses a contract it was not written for.
27
+ */
28
+ export const HOST_CONTRACT = 1;
29
+ /** The environment variable that tells the engine which command started it. */
30
+ export const INVOKER_VARIABLE = "GRIDA_FX_INVOKER";
31
+ /** The command each invoker's user types, without the verb. */
32
+ export const COMMANDS = {
33
+ "grida-fx": "grida-fx",
34
+ grida: "grida fx",
35
+ };
17
36
  /** Signals passed on to the engine. */
18
37
  export const FORWARDED = ["SIGINT", "SIGTERM", "SIGHUP", "SIGQUIT"];
19
38
  /** The same signal again within this many milliseconds is a repeat of one interruption. */
20
39
  export const REPEAT_MS = 250;
21
40
  /** The exit status of the command's own failures (no engine for this machine, …). */
22
41
  const FAILED = 1;
23
- /** Runs the engine with `argv` (the arguments after the command's name) and ends this process as
24
- * the engine ended. */
42
+ /** `@grida/fx`'s `grida-fx` command: {@link launch} as the `grida-fx` invoker. */
25
43
  export function main(argv) {
44
+ launch(argv, { invoker: "grida-fx" });
45
+ }
46
+ /** Runs the engine with `argv` (the arguments after the command's name, and after `fx` for
47
+ * `grida fx`) and ends this process as the engine ended. Throws a `TypeError`, before anything
48
+ * runs, for an invoker this contract does not know. */
49
+ export function launch(argv, options = {}) {
50
+ const invoker = options.invoker ?? "grida-fx";
51
+ if (!Object.hasOwn(COMMANDS, invoker)) {
52
+ throw new TypeError(`unknown invoker ${JSON.stringify(invoker)}: @grida/fx/cli contract ${HOST_CONTRACT} ` +
53
+ `knows ${Object.keys(COMMANDS).join(", ")}`);
54
+ }
55
+ const command = COMMANDS[invoker];
56
+ const env = { ...process.env, [INVOKER_VARIABLE]: invoker };
26
57
  let engine;
27
58
  try {
28
- engine = binary();
59
+ engine = binary({ env });
29
60
  }
30
61
  catch (error) {
31
- process.stderr.write(`grida-fx: ${error instanceof Error ? error.message : String(error)}\n`);
62
+ process.stderr.write(`${command}: ${error instanceof Error ? error.message : String(error)}\n`);
32
63
  process.exit(FAILED);
33
64
  }
34
65
  const unix = process.platform !== "win32";
35
- const child = spawn(engine, [...argv], { stdio: "inherit", detached: unix });
66
+ const child = spawn(engine, [...argv], { stdio: "inherit", detached: unix, env });
36
67
  const listeners = forwardSignals(child, unix);
37
68
  child.once("error", (error) => {
38
69
  listeners.remove();
39
- process.stderr.write(`grida-fx: could not start the engine (${engine}): ${error.message}\n`);
70
+ process.stderr.write(`${command}: could not start the engine (${engine}): ${error.message}\n`);
40
71
  process.exit(FAILED);
41
72
  });
42
73
  child.once("exit", (status, signal) => {
@@ -0,0 +1,42 @@
1
+ /** Exact-target run control through the engine's public command line (spec/control.md).
2
+ * The engine resolves and authenticates the owner and verifies cleanup. */
3
+ import { type CallOptions, type Exit } from "./engine.js";
4
+ import { FxError } from "./errors.js";
5
+ /** The engine's fx-run-control-v1 response. Wire fields retain lower_snake_case names. */
6
+ export interface RunControlResult {
7
+ readonly kind: "fx-run-control-v1";
8
+ readonly operation: "inspect" | "cancel";
9
+ readonly invocation_id: string | null;
10
+ readonly outcome: "inspected" | "accepted" | "already_requested" | "already_terminal" | "finishing" | "completed" | "error";
11
+ readonly request_status: "accepted" | "not_accepted" | "unknown";
12
+ readonly recorded_state: "planned" | "unfinished" | "succeeded" | "failed" | "cancelled" | "unknown";
13
+ readonly cleanup: "pending" | "complete" | "unknown";
14
+ readonly external_completion: "not_verified";
15
+ readonly code?: string;
16
+ readonly message?: string;
17
+ readonly availability?: "available" | "unavailable" | "unsupported" | "unknown";
18
+ readonly can_cancel?: boolean;
19
+ }
20
+ /** A structured control failure, retaining its stable code and complete result.
21
+ * Unsupported binaries and malformed responses reject with ordinary FxError. */
22
+ export declare class RunControlError extends FxError {
23
+ readonly result: RunControlResult;
24
+ readonly code: string;
25
+ constructor(result: RunControlResult, done: Exit);
26
+ }
27
+ /** Options of cancel. Relative targets start at cwd, as on the command line. */
28
+ export interface CancelOptions extends CallOptions {
29
+ /** Expected-current invocation guard. A successor is refused, never automatically selected. */
30
+ readonly invocation?: string;
31
+ /** Verify local completion, with a default timeout of thirty seconds. */
32
+ readonly wait?: boolean;
33
+ /** Positive integer followed by s, m or h (e.g. "5s"); requires wait: true. This bounds
34
+ * waiting only and never terminates the run or retracts an accepted cancellation. */
35
+ readonly timeout?: string;
36
+ }
37
+ /** Inspect one exact target's invocation and authenticated control availability. A bare
38
+ * workflow ID is refused by the engine; no latest-run selection is implied. */
39
+ export declare function inspectControl(run: string, options?: CallOptions): Promise<RunControlResult>;
40
+ /** Request cancellation of one invocation. Aborting this control client only ends its wait;
41
+ * an accepted cancellation remains effective in the separately owned runner. */
42
+ export declare function cancel(run: string, options?: CancelOptions): Promise<RunControlResult>;