@orgsdk/executor 0.0.0-stage → 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.
Files changed (80) hide show
  1. package/LICENSE +122 -0
  2. package/PROVENANCE.md +15 -0
  3. package/README.md +113 -2
  4. package/bin/orgsdk-executor.mjs +2 -0
  5. package/dist/cli-options.js +41 -0
  6. package/dist/cli.js +80 -0
  7. package/dist/client.js +116 -0
  8. package/dist/contract.js +102 -0
  9. package/dist/embedded-plugin-loader.mjs +56 -0
  10. package/dist/engine/plugins/namespace.js +157 -0
  11. package/dist/engine/plugins/types.js +0 -0
  12. package/dist/engine/retry.js +67 -0
  13. package/dist/engine/sandbox/context.js +115 -0
  14. package/dist/engine/sandbox/cpu-budget.js +16 -0
  15. package/dist/engine/sandbox/executor.js +196 -0
  16. package/dist/engine/sandbox/function-proxy.js +177 -0
  17. package/dist/engine/sandbox/index.js +6 -0
  18. package/dist/engine/sandbox/secret-refs.js +116 -0
  19. package/dist/engine/sandbox/trace.js +65 -0
  20. package/dist/engine/sandbox/transpile.js +51 -0
  21. package/dist/engine/sandbox/types.js +0 -0
  22. package/dist/engine/sandbox/validate.js +63 -0
  23. package/dist/engine/sandbox/webhook-handler.js +69 -0
  24. package/dist/engine/shared.js +14 -0
  25. package/dist/executor-configuration.js +44 -0
  26. package/dist/isolated-actions.js +188 -0
  27. package/dist/isolated-worker.js +232 -0
  28. package/dist/mcp/aliases.js +29 -0
  29. package/dist/mcp/client.js +239 -0
  30. package/dist/mcp/contract.js +57 -0
  31. package/dist/mcp/functions.js +40 -0
  32. package/dist/mcp/network.js +61 -0
  33. package/dist/mcp/schema-types.js +35 -0
  34. package/dist/mcp/transport.js +18 -0
  35. package/dist/package-dependencies.js +144 -0
  36. package/dist/package-plugin.js +151 -0
  37. package/dist/plugin-module.js +22 -0
  38. package/dist/plugin-store.js +159 -0
  39. package/dist/plugins.js +124 -0
  40. package/dist/process-runtime.js +72 -0
  41. package/dist/project-data.js +97 -0
  42. package/dist/project-files.js +259 -0
  43. package/dist/register-executor.js +23 -0
  44. package/dist/runner.js +239 -0
  45. package/dist/sdk-declarations.js +204 -0
  46. package/dist/session-job-contract.js +29 -0
  47. package/dist/session-job.js +256 -0
  48. package/dist/session-plugin-call.js +33 -0
  49. package/dist/sessions/cell-request.js +79 -0
  50. package/dist/sessions/compiler/analysis.js +86 -0
  51. package/dist/sessions/compiler/binding-pattern.js +35 -0
  52. package/dist/sessions/compiler/bindings.js +60 -0
  53. package/dist/sessions/compiler/emit.js +111 -0
  54. package/dist/sessions/compiler/references.js +62 -0
  55. package/dist/sessions/compiler/source-policy.js +62 -0
  56. package/dist/sessions/compiler.js +34 -0
  57. package/dist/sessions/configuration.js +68 -0
  58. package/dist/sessions/events.js +72 -0
  59. package/dist/sessions/execute-cell.js +80 -0
  60. package/dist/sessions/function-broker.js +78 -0
  61. package/dist/sessions/index.js +9 -0
  62. package/dist/sessions/journal.js +86 -0
  63. package/dist/sessions/kernel.js +142 -0
  64. package/dist/sessions/manager.js +155 -0
  65. package/dist/sessions/process.js +209 -0
  66. package/dist/sessions/records.js +61 -0
  67. package/dist/sessions/redaction.js +33 -0
  68. package/dist/sessions/scope.js +46 -0
  69. package/dist/sessions/session-runtime.js +155 -0
  70. package/dist/sessions/types.js +12 -0
  71. package/dist/sessions/values.js +40 -0
  72. package/dist/sessions/worker-guard.js +20 -0
  73. package/dist/sessions/worker.js +81 -0
  74. package/dist/spawn-job.js +69 -0
  75. package/dist/supervisor.js +224 -0
  76. package/dist/validate-code.js +114 -0
  77. package/dist/worker.js +57 -0
  78. package/package.json +58 -4
  79. package/scripts/install-service.sh +63 -0
  80. package/systemd/orgsdk-executor@.service +25 -0
package/LICENSE ADDED
@@ -0,0 +1,122 @@
1
+ OrgSDK Source-Available License
2
+ Version 1.0
3
+
4
+ Copyright (c) 2026 the OrgSDK copyright holders and contributors.
5
+
6
+ 1. Scope and acceptance
7
+
8
+ These terms apply to the OrgSDK material made available under this license,
9
+ including modifications of that material (the Software). The Licensor is each
10
+ copyright holder offering their material under these terms. Exercising a right
11
+ granted here means accepting these terms. Rights not expressly granted remain
12
+ with their holders.
13
+
14
+ Separately identified third-party material is governed by its own license. These
15
+ terms do not replace or restrict rights granted by third-party licenses. Retain
16
+ the applicable notices, including those accompanying dependencies and copied
17
+ source. These terms do not give ownership of your data, actions or outputs to
18
+ the Licensor.
19
+
20
+ 2. Source access and sharing
21
+
22
+ You may inspect, copy and modify the Software, and share original or modified
23
+ copies without charging for the copies. Every shared copy must include these
24
+ terms and retain applicable copyright, attribution and license notices.
25
+ Identify your modifications. Recipients obtain their rights directly under
26
+ these terms and must independently qualify for running the Software. You may
27
+ not offer broader rights to the covered material than you have received.
28
+
29
+ 3. Permitted operation without a separate agreement
30
+
31
+ You may run original or modified copies of the Software without a license fee:
32
+
33
+ (a) as an individual for your own personal, non-business activities; or
34
+ (b) for a business's own internal activities while its entire Organization
35
+ Group has fewer than 15 Staff.
36
+
37
+ Business activity performed by an individual on behalf of an organization is
38
+ subject to (b), including use through a personal account or personal computer.
39
+ The threshold is 0 through 14 Staff across the Organization Group, rather than
40
+ the number of users, accounts, projects, installations or concurrent sessions.
41
+ Part-time and full-time Staff each count as one person, counted only once.
42
+
43
+ An Organization Group is a business, sole trader or other business entity
44
+ together with all entities that control it, that it controls, or that are under
45
+ common control. Control means the ability to direct an entity's management,
46
+ whether through ownership, agreement or another arrangement.
47
+
48
+ Staff are working owners, employees, and individual contractors or agency
49
+ workers regularly working in the Organization Group's operations. Inactive
50
+ investors and suppliers merely providing goods or occasional services are not
51
+ Staff. Count Staff across the whole group, including people who do not use the
52
+ Software. Dividing an operation between entities, installations or accounts
53
+ does not reduce its Staff count.
54
+
55
+ An Organization Group with 15 or more Staff must obtain a separate written
56
+ commercial license before starting or continuing to run the Software. A group
57
+ that grows to that size must obtain that permission or stop running it.
58
+
59
+ 4. Hosting, resale and customer access
60
+
61
+ Regardless of Staff count, a separate written commercial license from the
62
+ relevant Licensor is required to:
63
+
64
+ (a) sell, rent, sublicense for a fee, or charge for copies of the Software;
65
+ (b) operate or host the Software for third parties as a service; or
66
+ (c) give customers or other third parties access to the Software's project,
67
+ action-authoring, execution, orchestration or management capabilities as
68
+ part of a product or service, including an embedded or white-label product.
69
+
70
+ These restrictions apply to direct access and to access through another user
71
+ interface, API, MCP endpoint, agent or intermediary. They apply when access is
72
+ free, charged separately, or bundled into another product or service. Renaming,
73
+ modifying or concealing the Software does not remove these restrictions.
74
+
75
+ A qualifying business may use the Software internally to carry out its own
76
+ work and deliver ordinary results to customers. Giving a customer a report or
77
+ other completed result does not by itself provide access to the Software.
78
+ Giving customers the ability to define, configure, submit or manage their own
79
+ work through the Software is access requiring a commercial license.
80
+
81
+ You may charge for consulting, installation, training, maintenance or custom
82
+ development for a qualifying recipient's own internal installation. The
83
+ recipient must control that installation, independently qualify under section
84
+ 3 or hold a commercial license, and retain control of its data and accounts.
85
+ Operation solely to install, develop or maintain that recipient-controlled
86
+ installation is assessed using the recipient's eligibility, rather than the
87
+ service provider's Staff count.
88
+ This permission does not include operating a hosted service for the recipient
89
+ or licensing use on behalf of an otherwise ineligible organization.
90
+
91
+ For permission beyond these terms, contact the maintainers through the OrgSDK
92
+ organization at https://github.com/OrgSDK. A separate written agreement may
93
+ grant additional rights to material its parties are authorized to license.
94
+
95
+ 5. Patents and branding
96
+
97
+ Each Licensor grants permission under patent claims it controls that would
98
+ necessarily be infringed by the unmodified Software, solely for activities
99
+ permitted by these terms. This does not cover infringement introduced by your
100
+ changes or combinations. If you bring a patent claim alleging that the
101
+ Software infringes a patent, your patent permission under this section ends.
102
+
103
+ No trademark or branding rights are granted, other than displaying the notices
104
+ required by these terms and accurately identifying the origin of the Software.
105
+ Do not imply endorsement of your modifications or services.
106
+
107
+ 6. Ending and restoring permission
108
+
109
+ Permission ends automatically when you breach these terms. If you correct the
110
+ breach within 30 days after first receiving written notice of it, permission
111
+ is restored. A later breach after such restoration requires written permission
112
+ from the relevant Licensor to restore your rights. Rights of recipients who
113
+ continue to comply with these terms are unaffected by your breach.
114
+
115
+ 7. Warranty and liability
116
+
117
+ To the extent allowed by applicable law, the Software is supplied without
118
+ warranties or promises about quality, fitness, availability, security or
119
+ non-infringement. You are responsible for evaluating and operating it. To that
120
+ same extent, the Licensor and contributors are not liable for losses or damages
121
+ arising from the Software or these terms. Nothing here excludes a right,
122
+ guarantee or liability that applicable law does not allow to be excluded.
package/PROVENANCE.md ADDED
@@ -0,0 +1,15 @@
1
+ # Retained OrgSDK engine
2
+
3
+ Source: OrgSDK/OrgSDK, commit 6cd23db588985072bddf8b9f4f64d512712b3494
4
+
5
+ This attribution is included in the executor npm package alongside the compiled
6
+ retained engine. It records origin and modifications; it does not grant a new license or
7
+ replace any applicable upstream copyright and permission notices.
8
+
9
+ Sandbox, CPU budgeting, TypeScript validation/transpilation, function proxies, secret redaction, plugin namespacing, plugin types and retry utilities are retained from packages/daemon/src. Local changes replace repository-specific logging/constants and the database AgentRow type. Product orchestration uses scoped OrgSDK HTTP APIs rather than the old AllStores/Postgres boot path. Original tests are retained where their dependencies belong to this extracted engine.
10
+
11
+ The eleven vendored product plugins and generated bundled catalog have been removed. Plugins are independently released, self-contained ESM artifacts, verified against the snapshot SHA256 before execution. No external plugin source is included in this package. The retained factory-context and safeFunctions adapter derives from the previously integrated OrgSDK plugin interface.
12
+
13
+ The project/action refactor removes the local OpenAI reasoning loop and chat-stream collector. The retained sandbox, plugin adapters, process isolation and execution tests continue to support code/actions and isolated validation/tests. Historical chat/delegation jobs fail explicitly; their removal does not replace the original vendor provenance.
14
+
15
+ Node portability changes replace Bun process, stream, timer, hashing and build APIs with Node standard-library APIs and esbuild. The npm artifact contains compiled JavaScript workers and retained SDK declarations; TypeScript sources and tests remain in the repository. These changes do not alter the HTTP-only product authority boundary or plugin digest verification.
package/README.md CHANGED
@@ -1,3 +1,114 @@
1
- # Temporary Holding Version
1
+ # Persistent project executor
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The `@orgsdk/executor` npm package provides `orgsdk-executor`. Install it with `npm install -g @orgsdk/executor` for an independently managed runner. The `@orgsdk/cli` platform package already includes its local executor. Linux with Node 22.22.0+ and npm is required. Bun 1.4 remains an optional source-development runtime; installed JavaScript workers do not require Bun on PATH. Docker execution additionally requires Docker with `--mount volume-subpath` support, a built executor image, and network access to the OrgSDK application.
4
+
5
+ Create an executor identity for the chosen project in the application. Register using its token on stdin (or `EXECUTOR_TOKEN`), without placing the token in command history:
6
+
7
+ ```sh
8
+ orgsdk-executor register --url http://localhost:8080 --data /path/to/private-runner
9
+ orgsdk-executor start --data /path/to/private-runner
10
+ ```
11
+
12
+ Registration saves the token in `registration.json` with mode 0600. Without `--data` or `EXECUTOR_DATA_DIR`, data lives at `$XDG_DATA_HOME/orgsdk/executor` (default `~/.local/share/orgsdk/executor`), independently of the package installation directory. Docker is the default mode. Configure `EXECUTOR_IMAGE`, `EXECUTION_NETWORK`, and `EXECUTOR_DATA_VOLUME`; set `--data` to the mounted volume root so it contains `agents/<agent-id>`. Docker jobs mount only their own agent subdirectory at `/agent`, use `/agent/workspace` as their working directory, and receive only their run capability through stdin. Other agents and registration files are not mounted. The managed installation runs `orgsdk-executor manage` (or `node dist/supervisor.js`) with `ORGSDK_SERVER_URL` and `LOCAL_EXECUTOR_BOOTSTRAP_TOKEN`. Each identity has one serial worker; revoked identities stop and remain stopped while the same revoked registration is advertised. Bootstrap omissions stop active workers; a later explicit re-enable or replacement identity starts a new worker. Transient startup failures retry with a bounded delay.
13
+
14
+ Use `start --mode host` explicitly to run child jobs using the current OS account, its PATH and HOME. Host mode can use installed command-line tools and their account configuration; it is appropriate only for trusted plugins. It filters bootstrap, token, password, API key and credential environment variables from child jobs. Plugin code still receives only snapshot-authorized product credentials through the run capability. Host processes retain OS account filesystem access. Host validation/test workers receive only the allowlisted source, SDK metadata, test fixtures and output schema, run in a disposable directory, and have no product capability or project mount. Their OS account can still access host files; Docker provides the OS isolation boundary. Docker is the default isolation boundary.
15
+
16
+ Project workspace files and installed plugin releases survive runs. No run cleanup deletes the agent folder. Plugins install under `agents/<id>/plugins/<slug>/<sha256>/plugin.mjs`; historical pinned versions remain available to retries. Current enabled configuration is fetched before each claim. External clients own reasoning and coordination. The runtime executes action, code, validation and test jobs only; built-in chat and reasoning delegation are retired. Existing `agents/<id>` storage paths and `--agent` install arguments identify retained project IDs.
17
+
18
+ [Execution sessions](src/sessions/README.md) keep successive cells in one live worker, with stable session IDs, cursor-based events and retained history after close or expiry. The executor advertises session support during registration and handles authenticated session commands in its project job loop.
19
+
20
+ ## External plugins
21
+
22
+ No built-in plugin implementations are shipped. Supply a self-contained ESM JavaScript release URL over HTTPS in `package_url`, its lowercase SHA256 as `digest`, and repository/source links in marketplace metadata. Up to five HTTPS redirects are followed (HTTP downgrades are rejected), streaming downloads are capped at 32 MiB, bytes are verified before import, and cached releases are verified without fetching again. Modules can export `safeFunctions` directly or a default context factory returning `safeFunctions`, optional `onLoad`, and optional Zod config schema. Inline custom plugins continue to accept TypeScript and positional handlers with the authorized secret as the first argument when configured. External factory handlers use the named canonical contract. The factory receives snapshot-scoped credential/config stores; mutation is denied. Bundle dependencies into the release. Raw npm packages and tarballs are not accepted by this version.
23
+
24
+ An administrator can preinstall a local bundle with the same digest checks. Leave `package_url` blank in the catalog for a release available only as a local file; each assigned agent needs its own installed copy:
25
+
26
+ ```sh
27
+ orgsdk-executor install --agent AGENT_ID --manifest manifest.json --file plugin.mjs --data /path/to/private-runner
28
+ ```
29
+
30
+ Runtime checks: `bun run check`. Run `npm run smoke:node` and `npm run smoke:bun` to pack and install into temporary storage, then exercise the same built-worker, plugin, validation/test, session and shutdown assertions under the selected runtime. The Node check removes Bun from PATH. The Bun check executes the suite and its CLI, job, validation, session and manager child processes with Bun. Both verify the executing runtime and clean their temporary fixtures. Source unit tests use `bun:test` and Bun HTTP/process fixtures, so `bun run check` remains a separate Bun-only gate; the packed behavioral suite supplies the matching Node/Bun coverage. Docker execution remains an opt-in integration check. Build JavaScript with `npm run build`; build a local installable artifact with `npm pack` (which runs the build automatically). Do not publish without separate authorization.
31
+
32
+ For an existing plugin checkout using the canonical `.plugin.json` with `name`, `version`, and `entry`, install its dependencies in that checkout, then run `orgsdk-executor package-plugin --directory CHECKOUT --output RELEASE_DIR`. This adapter uses esbuild to bundle the entry and installed dependencies into one ESM file and emits a manifest preserving the original plugin metadata (including any declared tools/docs/auth/config). The adapter accepts a checkout root containing `plugin/.plugin.json` or the plugin directory itself. It also emits `<slug>.catalog.json`, an array matching the OrgSDK marketplace catalog (tool schemas, documentation, auth metadata and configuration schema). Set the immutable HTTPS `package_url` in that catalog and configure `PLUGIN_CATALOG_PATH` to use it; `release_metadata` is pinned when installed. The companion manifest is for the local install command. The emitted digest pins the exact compiled bytes; reproducing the source build still requires the checkout's own dependency lock. Canonical source `.tgz` packages are not directly installed or executed. Local preinstall via `install --file` avoids a release server for development without weakening digest checks.
33
+
34
+ ## Install an optional local Linux service
35
+
36
+ Use this optional systemd service to run a project executor on a local Linux machine.
37
+ The service communicates with the application over HTTP and never accesses the application database.
38
+ Use `http://localhost:8080` when the service runs on the server machine, or the
39
+ server's reachable local network address when using another machine. Docker
40
+ jobs also need a server address reachable from their container; container
41
+ `localhost` refers to the job container itself. Allow outbound access to the
42
+ server, plugin release URLs and configured model providers. No inbound executor
43
+ port is needed. Create one executor identity per agent in the application; a
44
+ service instance uses that identity and processes one run at a time.
45
+
46
+ Build the npm artifact from `runtime/` with `npm pack`, and transfer the
47
+ resulting tarball to the local Linux machine if needed. Install Node 22.22.0+/npm and systemd, with Node in a system-wide path such as `/usr/local/bin/node`.
48
+ Docker mode also needs Docker
49
+ Engine. Extract the installer from the tarball and run it as root:
50
+
51
+ ```sh
52
+ tar -xzf orgsdk-executor-0.2.0.tgz package/scripts/install-service.sh
53
+ sudo bash package/scripts/install-service.sh "$PWD/orgsdk-executor-0.2.0.tgz" researcher docker
54
+ ```
55
+
56
+ The installer creates `/opt/orgsdk-executor`, the `orgsdk-researcher` system
57
+ account, `/var/lib/orgsdk-executor/researcher` (0700), the root-only environment
58
+ file `/etc/orgsdk-executor/researcher.env`, and a systemd template. It prints the
59
+ exact registration command with a silent shell token prompt and stdin pipe;
60
+ the token is never a command argument. Registration saves it as 0600 in the
61
+ private data directory. The service starts only after registration and your
62
+ explicit `systemctl enable --now orgsdk-executor@researcher` command. Replace
63
+ the printed `https://YOUR-SERVER` placeholder with your reachable local server URL.
64
+
65
+ For Docker mode, build the job image on the service machine from the repository
66
+ root with `docker build -t orgsdk-executor:local runtime`. When using another
67
+ local build machine, transfer the image with `docker save`/`docker load`. Set
68
+ `EXECUTOR_IMAGE` in the environment file to that image. The default
69
+ `EXECUTION_NETWORK=bridge` supports outbound server access. Each job bind-mounts
70
+ only its agent directory, runs as the service account's numeric UID/GID, and
71
+ receives a run capability through stdin. Registration and environment files
72
+ are outside that mount. Docker group access grants host administration power;
73
+ use a dedicated trusted executor machine.
74
+
75
+ For host execution, pass `host` to the installer explicitly. Host plugins run
76
+ under the instance account and can access its private files, including its
77
+ registration; use this mode only with trusted plugins. Docker is the default.
78
+ No bootstrap token is required for either service mode.
79
+
80
+ Repeat the installer with another instance name and register another agent to
81
+ add independent services and persistent folders. Package files are shared;
82
+ stop all executor services before upgrading the package, rerun the installer,
83
+ then restart them. Existing data and environment files are preserved. Inspect
84
+ logs with `journalctl -u orgsdk-executor@researcher`; stop a runner with
85
+ `systemctl stop orgsdk-executor@researcher`. Stopping does not delete files.
86
+ The artifact includes built JavaScript, workers, SDK declarations, and the embedded plugin loader. npm installs its production dependencies; it is not a standalone executable. Source TypeScript, tests and development fixtures are omitted.
87
+
88
+ ## Publishing compatible plugin bundles
89
+
90
+ `package-plugin` creates a standalone ESM release with dependencies bundled. Supply `--license FILE` when publishing to retain that first-party license plus the installed production dependency licenses in the bundle and its `.notices.txt` companion. Missing upstream license files must be supplied from their actual upstream source before publication; the builder never fetches licenses or changes source-repository visibility.
91
+
92
+ Some libraries (such as Playwright) need their original package-file layout. Opt in with `--embed-dependencies playwright`: the package carries a compressed dependency closure, validates every extracted file against its embedded SHA256 before loading, and uses a package-local directory. It does not depend on a checkout or a shared `node_modules` directory. Do not use this to distribute platform-specific native binaries as portable JavaScript.
93
+
94
+ Browser's engine is a runner prerequisite. The optional `Dockerfile.chromium` includes the Chromium version matching Playwright 1.60.0; it adds no plugin implementations to the platform:
95
+
96
+ ```sh
97
+ docker build -t orgsdk-job:chromium -f runtime/Dockerfile.chromium runtime
98
+ EXECUTOR_IMAGE=orgsdk-job:chromium orgsdk-executor start --mode docker
99
+ ```
100
+
101
+ Independently managed executors can select that image using `EXECUTOR_IMAGE`. Standard executors remain unchanged. Host-mode runners need matching Chromium at `PLAYWRIGHT_BROWSERS_PATH`.
102
+
103
+ Release acceptance can be repeated without a personal installation or provider API calls:
104
+
105
+ ```sh
106
+ bun --no-env-file runtime/scripts/verify-plugin-releases.ts \
107
+ --catalog https://orgsdk.ai/plugins/releases.json
108
+ ```
109
+
110
+ Use `--catalog /path/releases.json --bundle-root /path/bundles` before publication. Add `--render-pdf` when the matching engine is provisioned to exercise real PDF output. Every package is checksum-verified, installed in temporary `orgsdk-platform-test` project storage, and loaded to compare its exported tools to the catalog. Data Tools is exercised through the VM action interface. This does not prove provider OAuth setup or live external writes.
111
+
112
+ `ORGSDK_SERVER_URL` is the executor's application base URL. Point it at the application server, for example `http://127.0.0.1:8080`. The server binary does not include or start the executor. Separately managed executors must configure `ORGSDK_SERVER_URL` when upgrading; the platform CLI and managed development command supply it automatically.
113
+
114
+ Protocol 4 adds project-owned remote MCP discovery and execution over Streamable HTTP or legacy HTTP/SSE. Connections and reviewed tool schemas are supplied in immutable jobs; authentication headers are retrieved using run-scoped credentials. Each run owns and closes its connections. No stdio servers are launched. See the platform [remote MCP guide](../docs/remote-mcp.md).
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ await import("../dist/cli.js");
@@ -0,0 +1,41 @@
1
+ // src/cli-options.ts
2
+ import { parseArgs } from "node:util";
3
+ var commandOptions = {
4
+ register: ["url", "data"],
5
+ start: ["mode", "data"],
6
+ manage: ["mode", "data"],
7
+ install: ["agent", "manifest", "file", "data"],
8
+ "package-plugin": ["directory", "output", "embed-dependencies", "license"]
9
+ };
10
+ function executorArguments(args) {
11
+ const command = args[0] ?? "--help";
12
+ if (command === "--help" || command === "--version") {
13
+ if (args.length > 1)
14
+ throw new Error("Help and version do not accept arguments");
15
+ return {
16
+ command,
17
+ option: (_name) => void 0
18
+ };
19
+ }
20
+ const allowed = commandOptions[command];
21
+ if (!allowed) throw new Error("Unknown executor command; use --help");
22
+ const { values } = parseArgs({
23
+ args: args.slice(1),
24
+ options: Object.fromEntries(
25
+ allowed.map((name) => [name, { type: "string" }])
26
+ ),
27
+ strict: true,
28
+ allowPositionals: false
29
+ });
30
+ for (const [name, value] of Object.entries(values)) {
31
+ if (typeof value !== "string" || !value.trim())
32
+ throw new Error(`--${name} requires a nonempty value`);
33
+ }
34
+ return {
35
+ command,
36
+ option: (name) => values[name]
37
+ };
38
+ }
39
+ export {
40
+ executorArguments
41
+ };
package/dist/cli.js ADDED
@@ -0,0 +1,80 @@
1
+ // src/cli.ts
2
+ import { homedir } from "node:os";
3
+ import { executorArguments } from "./cli-options.js";
4
+ import { readStdin } from "./process-runtime.js";
5
+ import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
6
+ import { resolve, join } from "node:path";
7
+ import { z } from "zod";
8
+ import { Client } from "./client.js";
9
+ import { manage, registrationSchema, runAgent } from "./supervisor.js";
10
+ import { installPlugin } from "./plugin-store.js";
11
+ import { pluginSchema } from "./contract.js";
12
+ import { registerExecutor } from "./register-executor.js";
13
+ import { packagePlugin } from "./package-plugin.js";
14
+ var { command, option } = executorArguments(process.argv.slice(2));
15
+ var registerResponseSchema = z.object({
16
+ id: z.string(),
17
+ agent_id: z.string()
18
+ });
19
+ var modeSchema = z.enum(["docker", "host"]);
20
+ var data = resolve(
21
+ option("data") || process.env.EXECUTOR_DATA_DIR || join(
22
+ process.env.XDG_DATA_HOME || join(homedir(), ".local", "share"),
23
+ "orgsdk",
24
+ "executor"
25
+ )
26
+ );
27
+ process.env.EXECUTOR_DATA_DIR = data;
28
+ var file = join(data, "registration.json");
29
+ if (command === "--help" || !command) {
30
+ console.log(
31
+ "orgsdk-executor register --url URL [--data DIR] (token: EXECUTOR_TOKEN or stdin)\norgsdk-executor start [--mode docker|host] [--data DIR]\norgsdk-executor install --agent ID --manifest FILE [--file bundled.mjs] [--data DIR]\norgsdk-executor package-plugin --directory CHECKOUT --output DIR [--embed-dependencies package,...] [--license FILE]\norgsdk-executor manage [--mode docker|host] (bootstrap manager)"
32
+ );
33
+ } else if (command === "--version") {
34
+ console.log("0.1.1");
35
+ } else if (command === "register") {
36
+ const base = z.string().url().parse(option("url") || process.env.ORGSDK_SERVER_URL);
37
+ const token = z.string().min(32).parse(process.env.EXECUTOR_TOKEN || (await readStdin()).trim());
38
+ const registration = registerResponseSchema.parse(
39
+ await registerExecutor(new Client(base, token))
40
+ );
41
+ await mkdir(data, { recursive: true, mode: 448 });
42
+ await writeFile(
43
+ file,
44
+ JSON.stringify({
45
+ base,
46
+ agent_id: registration.agent_id,
47
+ executor_id: registration.id,
48
+ token
49
+ }),
50
+ { mode: 384 }
51
+ );
52
+ await chmod(file, 384);
53
+ console.log(`Registered executor for agent ${registration.agent_id}`);
54
+ } else if (command === "start") {
55
+ const config = registrationSchema.extend({ base: z.string().url() }).parse(JSON.parse(await readFile(file, "utf8")));
56
+ await runAgent(
57
+ config.base,
58
+ config,
59
+ modeSchema.parse(option("mode") || "docker")
60
+ );
61
+ } else if (command === "manage")
62
+ await manage(modeSchema.parse(option("mode") || "docker"));
63
+ else if (command === "package-plugin")
64
+ await packagePlugin(
65
+ z.string().parse(option("directory")),
66
+ option("output") || "plugin-release",
67
+ option("embed-dependencies")?.split(",").filter(Boolean),
68
+ option("license")
69
+ );
70
+ else if (command === "install") {
71
+ const plugin = pluginSchema.parse(
72
+ JSON.parse(await readFile(z.string().parse(option("manifest")), "utf8"))
73
+ );
74
+ await installPlugin(
75
+ plugin,
76
+ z.string().parse(option("agent")),
77
+ option("file")
78
+ );
79
+ console.log(`Installed ${plugin.slug}@${plugin.version}`);
80
+ } else throw new Error("Unknown executor command; use --help");
package/dist/client.js ADDED
@@ -0,0 +1,116 @@
1
+ // src/client.ts
2
+ import { z } from "zod";
3
+ import { withRetry } from "./engine/retry.js";
4
+ function identifier(value) {
5
+ return z.string().regex(/^[a-zA-Z0-9_-]+$/).parse(value);
6
+ }
7
+ var Client = class {
8
+ constructor(base, token, signal) {
9
+ this.base = base;
10
+ this.token = token;
11
+ this.signal = signal;
12
+ }
13
+ base;
14
+ token;
15
+ signal;
16
+ register(input) {
17
+ return this.#request("/internal/execution/v1/register/", "POST", input);
18
+ }
19
+ configuration() {
20
+ return this.#request("/internal/execution/v1/configuration/", "GET");
21
+ }
22
+ claim() {
23
+ return this.#request("/internal/execution/v1/claim/", "POST");
24
+ }
25
+ bootstrap() {
26
+ return this.#request("/internal/execution/v1/bootstrap/", "POST");
27
+ }
28
+ heartbeat(runId) {
29
+ return this.#request(
30
+ `/internal/execution/v1/runs/${identifier(runId)}/heartbeat/`,
31
+ "POST",
32
+ {}
33
+ );
34
+ }
35
+ publishEvent(runId, event) {
36
+ return this.#request(
37
+ `/internal/execution/v1/runs/${identifier(runId)}/events/`,
38
+ "POST",
39
+ event
40
+ );
41
+ }
42
+ complete(runId, result) {
43
+ return this.#request(
44
+ `/internal/execution/v1/runs/${identifier(runId)}/complete/`,
45
+ "POST",
46
+ result
47
+ );
48
+ }
49
+ createApproval(input) {
50
+ return this.#request(
51
+ "/internal/execution/v1/product/approvals/",
52
+ "POST",
53
+ input
54
+ );
55
+ }
56
+ approval(id) {
57
+ return this.#request(
58
+ `/internal/execution/v1/product/approvals/${identifier(id)}/`,
59
+ "GET"
60
+ );
61
+ }
62
+ saveArtifact(input) {
63
+ return this.#request(
64
+ "/internal/execution/v1/product/artifacts/",
65
+ "POST",
66
+ input
67
+ );
68
+ }
69
+ projectData(operation, params) {
70
+ return this.#request(
71
+ "/internal/execution/v1/product/project-data/",
72
+ "POST",
73
+ { ...params, operation }
74
+ );
75
+ }
76
+ async secret(id) {
77
+ const result = await this.#request(
78
+ `/internal/execution/v1/credentials/${identifier(id)}/`,
79
+ "GET"
80
+ );
81
+ return z.object({ secret: z.record(z.string(), z.unknown()) }).parse(result).secret;
82
+ }
83
+ async #request(path, method, body) {
84
+ const response = await withRetry(
85
+ async () => {
86
+ const result = await fetch(`${this.base.replace(/\/$/, "")}${path}`, {
87
+ method,
88
+ headers: {
89
+ Authorization: `Bearer ${this.token}`,
90
+ "Content-Type": "application/json"
91
+ },
92
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
93
+ signal: this.signal ? AbortSignal.any([this.signal, AbortSignal.timeout(15e3)]) : AbortSignal.timeout(15e3),
94
+ redirect: "error"
95
+ });
96
+ if (result.status >= 500) {
97
+ throw new Error(`API ${result.status}`);
98
+ }
99
+ return result;
100
+ },
101
+ { maxRetries: method === "GET" ? 2 : 0 }
102
+ );
103
+ if (!response.ok) {
104
+ throw new Error(
105
+ `API ${response.status}: ${(await response.text()).slice(0, 500)}`
106
+ );
107
+ }
108
+ if (response.status === 204) {
109
+ return void 0;
110
+ }
111
+ return response.json();
112
+ }
113
+ };
114
+ export {
115
+ Client
116
+ };
@@ -0,0 +1,102 @@
1
+ // src/contract.ts
2
+ import { z } from "zod";
3
+ import {
4
+ sessionCommandSchema,
5
+ sessionScopeSchema
6
+ } from "./session-job-contract.js";
7
+ import { connectionSchema } from "./mcp/contract.js";
8
+ var pluginSchema = z.object({
9
+ distribution: z.enum(["inline", "external", "mcp"]).optional(),
10
+ mcp: connectionSchema.optional(),
11
+ package_url: z.string().optional(),
12
+ configuration: z.record(z.string(), z.unknown()).optional(),
13
+ credential_provider: z.string().nullable().optional(),
14
+ contract_version: z.literal(1).optional(),
15
+ slug: z.string(),
16
+ version: z.string(),
17
+ source: z.string(),
18
+ digest: z.string(),
19
+ credential_id: z.string().nullable()
20
+ });
21
+ var agentSchema = z.object({
22
+ id: z.string(),
23
+ name: z.string(),
24
+ plugins: z.array(pluginSchema),
25
+ resources: z.object({
26
+ tables: z.object({
27
+ read: z.array(z.string().uuid()),
28
+ write: z.array(z.string().uuid())
29
+ }),
30
+ documents: z.object({
31
+ read: z.array(z.string().uuid()),
32
+ write: z.array(z.string().uuid())
33
+ })
34
+ }).optional()
35
+ });
36
+ var jobSchema = z.object({
37
+ protocol_version: z.union([
38
+ z.literal(1),
39
+ z.literal(2),
40
+ z.literal(3),
41
+ z.literal(4)
42
+ ]),
43
+ run_id: z.string().uuid(),
44
+ workspace_id: z.number(),
45
+ actor_id: z.number(),
46
+ operation: z.enum([
47
+ "action",
48
+ "chat",
49
+ "code",
50
+ "validate",
51
+ "test",
52
+ "mcp_discover",
53
+ "session"
54
+ ]),
55
+ capability: z.string(),
56
+ inputs: z.record(z.string(), z.unknown()),
57
+ deadline: z.string(),
58
+ lease_seconds: z.number(),
59
+ snapshot: z.object({
60
+ mcp_discovery: connectionSchema.optional(),
61
+ session: sessionCommandSchema.optional(),
62
+ session_scope: sessionScopeSchema.optional(),
63
+ agents: z.array(agentSchema),
64
+ root_agent_id: z.string(),
65
+ validation_mode: z.enum(["legacy", "semantic"]).optional(),
66
+ sdk: z.unknown().optional(),
67
+ input_schema: z.record(z.string(), z.json()).nullable().optional(),
68
+ output_schema: z.record(z.string(), z.json()).nullable().optional(),
69
+ test_suite: z.object({
70
+ id: z.string().optional(),
71
+ revision: z.number().optional(),
72
+ digest: z.string().optional(),
73
+ cases: z.array(z.unknown())
74
+ }).optional(),
75
+ source: z.string().optional(),
76
+ source_digest: z.string().optional(),
77
+ version: z.number().optional(),
78
+ sdk_revision: z.number().int().optional(),
79
+ configuration_revision: z.string().optional()
80
+ })
81
+ }).refine(
82
+ (job) => job.protocol_version === 4 || job.operation !== "mcp_discover" && !job.snapshot.mcp_discovery && !job.snapshot.agents.some(
83
+ (agent) => agent.plugins.some((plugin) => plugin.distribution === "mcp")
84
+ ),
85
+ { message: "MCP connections require protocol version 4" }
86
+ ).refine(
87
+ (job) => job.operation !== "code" || [2, 4].includes(job.protocol_version),
88
+ {
89
+ message: "Code execution requires protocol version 2"
90
+ }
91
+ ).refine(
92
+ (job) => !["validate", "test"].includes(job.operation) && job.snapshot.validation_mode !== "semantic" || [3, 4].includes(job.protocol_version),
93
+ { message: "Semantic validation and tests require protocol version 3" }
94
+ ).refine(
95
+ (job) => job.operation !== "session" || job.protocol_version === 4 && job.snapshot.session !== void 0 && job.snapshot.session_scope?.projectId === job.snapshot.root_agent_id && job.snapshot.session_scope.workspaceId === String(job.workspace_id) && (job.snapshot.session.operation !== "execute" || typeof job.snapshot.source === "string"),
96
+ { message: "Invalid execution session job" }
97
+ );
98
+ export {
99
+ agentSchema,
100
+ jobSchema,
101
+ pluginSchema
102
+ };
@@ -0,0 +1,56 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, lstat, readFile, writeFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+ import { gunzipSync } from "node:zlib";
6
+
7
+ async function ensureDirectory(path) {
8
+ const parent = dirname(path);
9
+ if (parent !== path) await ensureDirectory(parent);
10
+ try {
11
+ await mkdir(path, { mode: 0o700 });
12
+ } catch (error) {
13
+ if (error.code !== "EEXIST") throw error;
14
+ }
15
+ const stat = await lstat(path);
16
+ if (!stat.isDirectory() || stat.isSymbolicLink())
17
+ throw new Error("Unsafe embedded plugin dependency directory");
18
+ }
19
+
20
+ export async function loadEmbeddedPlugin(encoded, moduleUrl) {
21
+ const digest = createHash("sha256").update(encoded).digest("hex");
22
+ const root = fileURLToPath(new URL(`./.embedded/${digest}/`, moduleUrl));
23
+ const files = JSON.parse(
24
+ gunzipSync(Buffer.from(encoded, "base64")).toString("utf8"),
25
+ );
26
+ for (const [relativePath, content, expectedDigest] of files) {
27
+ const parts = relativePath.split("/");
28
+ if (
29
+ parts.some(
30
+ (part) => !part || part === "." || part === ".." || part.includes("\\"),
31
+ )
32
+ )
33
+ throw new Error("Unsafe embedded plugin dependency path");
34
+ const path = join(root, ...parts);
35
+ await ensureDirectory(dirname(path));
36
+ try {
37
+ await writeFile(path, Buffer.from(content, "base64"), {
38
+ flag: "wx",
39
+ mode: 0o600,
40
+ });
41
+ } catch (error) {
42
+ if (error.code !== "EEXIST") throw error;
43
+ }
44
+ const stat = await lstat(path);
45
+ if (!stat.isFile() || stat.isSymbolicLink())
46
+ throw new Error("Unsafe embedded plugin dependency file");
47
+ if (
48
+ createHash("sha256")
49
+ .update(await readFile(path))
50
+ .digest("hex") !== expectedDigest
51
+ )
52
+ throw new Error("Embedded plugin dependency digest mismatch");
53
+ }
54
+ const module = await import(pathToFileURL(join(root, "entry.mjs")).href);
55
+ return module.default ?? module;
56
+ }