@syntropika/tembra-sdk 0.0.0-stage → 0.1.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 (130) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +47 -2
  3. package/dist/authoring/declaration.d.ts +47 -0
  4. package/dist/authoring/hooks.d.ts +11 -0
  5. package/dist/authoring/orb.d.ts +3 -0
  6. package/dist/authoring/types.d.ts +166 -0
  7. package/dist/bridge/identifiers.d.ts +207 -0
  8. package/dist/bridge/kernel.d.ts +117 -0
  9. package/dist/bridge/protocol.d.ts +181 -0
  10. package/dist/browser.d.ts +21 -0
  11. package/dist/browser.js +3282 -0
  12. package/dist/codec.d.ts +1 -0
  13. package/dist/codecs/json.d.ts +13 -0
  14. package/dist/codecs/msgpack.d.ts +3 -0
  15. package/dist/context-key.d.ts +35 -0
  16. package/dist/coordinator.d.ts +1 -0
  17. package/dist/coordinator.js +543 -0
  18. package/dist/embedded.d.ts +1 -0
  19. package/dist/embedded.js +1 -0
  20. package/dist/error.d.ts +13 -0
  21. package/dist/errors.d.ts +122 -0
  22. package/dist/hooks.d.ts +1 -0
  23. package/dist/host.d.ts +96 -0
  24. package/dist/host.js +3225 -0
  25. package/dist/identifiers.d.ts +1 -0
  26. package/dist/index.d.ts +12 -0
  27. package/dist/index.js +833 -0
  28. package/dist/infrastructure/coordinator.d.ts +13 -0
  29. package/dist/infrastructure/manager.d.ts +23 -0
  30. package/dist/infrastructure/rpc/channel.d.ts +52 -0
  31. package/dist/infrastructure/rpc/client.d.ts +20 -0
  32. package/dist/infrastructure/rpc/server.d.ts +10 -0
  33. package/dist/infrastructure/rpc/state.d.ts +16 -0
  34. package/dist/kernel.d.ts +1 -0
  35. package/dist/manager.d.ts +1 -0
  36. package/dist/manager.js +390 -0
  37. package/dist/msgpack.d.ts +1 -0
  38. package/dist/msgpack.js +635 -0
  39. package/dist/node.d.ts +14 -0
  40. package/dist/node.js +3283 -0
  41. package/dist/orb.d.ts +1 -0
  42. package/dist/protocol.d.ts +1 -0
  43. package/dist/rpc.d.ts +3 -0
  44. package/dist/rpc.js +1036 -0
  45. package/dist/runtime/activities.d.ts +30 -0
  46. package/dist/runtime/calls.d.ts +22 -0
  47. package/dist/runtime/context.d.ts +37 -0
  48. package/dist/runtime/declaration.d.ts +1 -0
  49. package/dist/runtime/lifecycle.d.ts +28 -0
  50. package/dist/runtime/orbs.d.ts +39 -0
  51. package/dist/runtime/programs.d.ts +31 -0
  52. package/dist/runtime/records.d.ts +107 -0
  53. package/dist/runtime/references.d.ts +38 -0
  54. package/dist/runtime/reload.d.ts +17 -0
  55. package/dist/runtime/resources.d.ts +24 -0
  56. package/dist/runtime/scopes.d.ts +35 -0
  57. package/dist/runtime/session.d.ts +69 -0
  58. package/dist/state/binding.d.ts +28 -0
  59. package/dist/state/selection.d.ts +21 -0
  60. package/dist/state/types.d.ts +35 -0
  61. package/dist/state.d.ts +2 -0
  62. package/dist/telemetry.d.ts +23 -0
  63. package/dist/telemetry.js +27 -0
  64. package/dist/tooling/build.d.ts +3 -0
  65. package/dist/tooling/index.d.ts +2 -0
  66. package/dist/tooling/index.js +181 -0
  67. package/dist/tooling/resolver.d.ts +5 -0
  68. package/dist/tooling/typecheck.d.ts +2 -0
  69. package/dist/tooling/types.d.ts +29 -0
  70. package/dist/types.d.ts +1 -0
  71. package/dist/values.d.ts +23 -0
  72. package/package.json +103 -4
  73. package/src/authoring/declaration.ts +220 -0
  74. package/src/authoring/hooks.ts +101 -0
  75. package/src/authoring/orb.ts +77 -0
  76. package/src/authoring/types.ts +212 -0
  77. package/src/bridge/identifiers.ts +212 -0
  78. package/src/bridge/kernel.ts +117 -0
  79. package/src/bridge/protocol.ts +193 -0
  80. package/src/browser.ts +59 -0
  81. package/src/codec.ts +1 -0
  82. package/src/codecs/json.ts +147 -0
  83. package/src/codecs/msgpack.ts +26 -0
  84. package/src/context-key.ts +94 -0
  85. package/src/coordinator.ts +1 -0
  86. package/src/embedded.ts +293 -0
  87. package/src/error.ts +50 -0
  88. package/src/errors.ts +237 -0
  89. package/src/hooks.ts +1 -0
  90. package/src/host.ts +142 -0
  91. package/src/identifiers.ts +1 -0
  92. package/src/index.ts +22 -0
  93. package/src/infrastructure/coordinator.ts +76 -0
  94. package/src/infrastructure/manager.ts +77 -0
  95. package/src/infrastructure/rpc/channel.ts +88 -0
  96. package/src/infrastructure/rpc/client.ts +161 -0
  97. package/src/infrastructure/rpc/server.ts +201 -0
  98. package/src/infrastructure/rpc/state.ts +70 -0
  99. package/src/kernel.ts +1 -0
  100. package/src/manager.ts +1 -0
  101. package/src/msgpack.ts +1 -0
  102. package/src/node.ts +53 -0
  103. package/src/orb.ts +1 -0
  104. package/src/protocol.ts +1 -0
  105. package/src/rpc.ts +3 -0
  106. package/src/runtime/activities.ts +197 -0
  107. package/src/runtime/calls.ts +165 -0
  108. package/src/runtime/context.ts +113 -0
  109. package/src/runtime/declaration.ts +1 -0
  110. package/src/runtime/lifecycle.ts +227 -0
  111. package/src/runtime/orbs.ts +292 -0
  112. package/src/runtime/programs.ts +274 -0
  113. package/src/runtime/records.ts +127 -0
  114. package/src/runtime/references.ts +398 -0
  115. package/src/runtime/reload.ts +161 -0
  116. package/src/runtime/resources.ts +157 -0
  117. package/src/runtime/scopes.ts +210 -0
  118. package/src/runtime/session.ts +181 -0
  119. package/src/state/binding.ts +157 -0
  120. package/src/state/selection.ts +122 -0
  121. package/src/state/types.ts +47 -0
  122. package/src/state.ts +2 -0
  123. package/src/telemetry.ts +45 -0
  124. package/src/tooling/build.ts +83 -0
  125. package/src/tooling/index.ts +8 -0
  126. package/src/tooling/resolver.ts +95 -0
  127. package/src/tooling/typecheck.ts +32 -0
  128. package/src/tooling/types.ts +32 -0
  129. package/src/types.ts +1 -0
  130. package/src/values.ts +85 -0
@@ -0,0 +1,181 @@
1
+ // src/tooling/build.ts
2
+ import { createHash } from "node:crypto";
3
+ import { mkdir, rename, writeFile } from "node:fs/promises";
4
+ import path2 from "node:path";
5
+ import ts3 from "typescript";
6
+
7
+ // src/tooling/resolver.ts
8
+ import resolve from "enhanced-resolve";
9
+ import fs from "node:fs";
10
+ import { readFile } from "node:fs/promises";
11
+ import { builtinModules } from "node:module";
12
+ import path from "node:path";
13
+ import ts from "typescript";
14
+
15
+ // src/tooling/types.ts
16
+ var Platform = Object.freeze({
17
+ Browser: "browser",
18
+ Worker: "worker",
19
+ Node: "node",
20
+ Embedded: "embedded"
21
+ });
22
+ function defineConfig(config) {
23
+ return config;
24
+ }
25
+
26
+ // src/tooling/resolver.ts
27
+ function external(specifier, target) {
28
+ return target.platform === Platform.Node && (builtinModules.includes(specifier.replace(/^node:/, "")) || (target.nativeExternals ?? []).some((name) => specifier === name || specifier.startsWith(`${name}/`)));
29
+ }
30
+ function resolver(root, target) {
31
+ const web = target.platform === Platform.Browser || target.platform === Platform.Worker;
32
+ const resolveModule = resolve.create.sync({
33
+ fileSystem: fs,
34
+ conditionNames: [
35
+ "source",
36
+ ...web ? ["browser"] : target.platform === Platform.Node ? ["node", "node-addons"] : ["tembra-embedded"],
37
+ "import",
38
+ "default"
39
+ ],
40
+ extensions: [".ts", ".tsx", ".mts", ".js", ".jsx", ".mjs", ".cjs", ".json"],
41
+ extensionAlias: { ".js": [".ts", ".tsx", ".js"], ".mjs": [".mts", ".mjs"] },
42
+ mainFields: web ? ["browser", "module", "main"] : ["module", "main"],
43
+ aliasFields: web ? ["browser"] : []
44
+ });
45
+ return {
46
+ name: "tembra-platform",
47
+ setup(builder) {
48
+ builder.onResolve({ filter: /^tembra:entry$/ }, () => ({
49
+ path: "entry",
50
+ namespace: "tembra-orb"
51
+ }));
52
+ builder.onLoad({ filter: /.*/, namespace: "tembra-orb" }, () => ({
53
+ contents: `import orb from ${JSON.stringify(path.resolve(root, target.entry))}; globalThis.__tembraOrb = orb;`,
54
+ loader: "js"
55
+ }));
56
+ builder.onResolve({ filter: /.*/ }, (request) => {
57
+ if (external(request.path, target))
58
+ return { path: request.path, external: true };
59
+ if (request.path.startsWith("node:") || request.path.startsWith("bun:") || builtinModules.includes(request.path))
60
+ throw new Error(`${request.importer}: ${request.path} requires its host runtime`);
61
+ if (request.kind === "entry-point-build")
62
+ return;
63
+ const resolved = resolveModule(path.dirname(request.importer || path.join(root, "entry.js")), request.path);
64
+ if (!resolved)
65
+ throw new Error(`${request.importer}: no compatible implementation for ${request.path}`);
66
+ if (resolved.endsWith(".node"))
67
+ throw new Error("Declare native Node packages as nativeExternals in a node build");
68
+ return { path: resolved };
69
+ });
70
+ builder.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async (request) => {
71
+ const source = await readFile(request.path, "utf8");
72
+ const parsed = ts.createSourceFile(request.path, source, ts.ScriptTarget.Latest, true);
73
+ function check(node) {
74
+ if (ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword || ts.isIdentifier(node.expression) && node.expression.text === "require")) {
75
+ const argument = node.arguments[0];
76
+ if (!argument || !ts.isStringLiteralLike(argument))
77
+ throw new Error(`${request.path}: dynamic module names must be resolved before publishing an orb`);
78
+ }
79
+ ts.forEachChild(node, check);
80
+ }
81
+ check(parsed);
82
+ return;
83
+ });
84
+ }
85
+ };
86
+ }
87
+
88
+ // src/tooling/typecheck.ts
89
+ import ts2 from "typescript";
90
+ function typecheck(entry, root) {
91
+ const configFile = ts2.findConfigFile(root, ts2.sys.fileExists);
92
+ const loaded = configFile ? ts2.readConfigFile(configFile, ts2.sys.readFile) : { config: {} };
93
+ if (loaded.error)
94
+ throw new Error(ts2.flattenDiagnosticMessageText(loaded.error.messageText, `
95
+ `));
96
+ const parsed = ts2.parseJsonConfigFileContent(loaded.config, ts2.sys, root);
97
+ const program = ts2.createProgram([entry], {
98
+ ...parsed.options,
99
+ target: ts2.ScriptTarget.ES2023,
100
+ module: ts2.ModuleKind.ESNext,
101
+ moduleResolution: ts2.ModuleResolutionKind.Bundler,
102
+ allowImportingTsExtensions: true,
103
+ noEmit: true,
104
+ strict: true,
105
+ skipLibCheck: true
106
+ });
107
+ const diagnostics = ts2.getPreEmitDiagnostics(program);
108
+ if (diagnostics.length)
109
+ throw new Error(ts2.formatDiagnosticsWithColorAndContext(diagnostics, {
110
+ getCurrentDirectory: () => root,
111
+ getCanonicalFileName: (name) => name,
112
+ getNewLine: () => `
113
+ `
114
+ }));
115
+ }
116
+
117
+ // src/tooling/build.ts
118
+ async function build(config) {
119
+ const root = path2.resolve(config.root ?? process.cwd());
120
+ const outDir = path2.resolve(root, config.outDir ?? "dist/tembra");
121
+ const artifacts = [];
122
+ for (const [name, target] of Object.entries(config.builds)) {
123
+ let verify = function(node) {
124
+ let specifier;
125
+ if (ts3.isImportDeclaration(node) || ts3.isExportDeclaration(node))
126
+ specifier = node.moduleSpecifier;
127
+ if (ts3.isCallExpression(node) && node.expression.kind === ts3.SyntaxKind.ImportKeyword)
128
+ specifier = node.arguments[0];
129
+ if (specifier && (!ts3.isStringLiteralLike(specifier) || !external(specifier.text, target)))
130
+ throw new Error(`Build ${name} contains an unresolved import`);
131
+ ts3.forEachChild(node, verify);
132
+ };
133
+ if (!/^[\w-]+$/.test(name) || !Object.values(Platform).includes(target.platform))
134
+ throw new Error("Invalid build name or platform");
135
+ const entry = path2.resolve(root, target.entry);
136
+ if (target.typecheck !== false)
137
+ typecheck(entry, root);
138
+ const result = await Bun.build({
139
+ entrypoints: [target.platform === Platform.Embedded ? "tembra:entry" : entry],
140
+ root,
141
+ format: target.platform === Platform.Embedded ? "iife" : "esm",
142
+ target: target.platform === Platform.Node ? "node" : "browser",
143
+ splitting: false,
144
+ minify: target.minify ?? true,
145
+ ...target.define ? { define: { ...target.define } } : {},
146
+ plugins: [resolver(root, target)]
147
+ });
148
+ if (!result.success)
149
+ throw new AggregateError(result.logs, `Build ${name} failed`);
150
+ if (result.outputs.length !== 1 || result.outputs[0]?.kind !== "entry-point")
151
+ throw new Error(`Build ${name} requires external assets; publish them explicitly instead of silently expanding the orb bundle`);
152
+ const output = result.outputs[0];
153
+ const source = await output.text();
154
+ const parsed = ts3.createSourceFile("bundle.js", source, ts3.ScriptTarget.Latest, true, ts3.ScriptKind.JS);
155
+ const hasDefault = parsed.statements.some((statement) => ts3.isExportAssignment(statement) || ts3.isExportDeclaration(statement) && statement.exportClause && ts3.isNamedExports(statement.exportClause) && statement.exportClause.elements.some((element) => element.name.text === "default"));
156
+ if (target.platform !== Platform.Embedded && !hasDefault)
157
+ throw new Error(`Build ${name} must export a default orb`);
158
+ verify(parsed);
159
+ const bytes = Buffer.from(source);
160
+ const hash = createHash("sha256").update(bytes).digest("hex");
161
+ const directory = path2.join(outDir, name);
162
+ const destination = path2.join(directory, `orb.${hash}.js`);
163
+ await mkdir(directory, { recursive: true });
164
+ const temporary = `${destination}.${process.pid}.tmp`;
165
+ await writeFile(temporary, bytes);
166
+ await rename(temporary, destination);
167
+ artifacts.push({
168
+ name,
169
+ platform: target.platform,
170
+ path: destination,
171
+ sha256: hash,
172
+ bytes: bytes.length
173
+ });
174
+ }
175
+ return artifacts;
176
+ }
177
+ export {
178
+ Platform,
179
+ build,
180
+ defineConfig
181
+ };
@@ -0,0 +1,5 @@
1
+ import { type BuildTarget } from "./types.ts";
2
+ /** Check whether the selected target permits this external dependency. */
3
+ export declare function external(specifier: string, target: BuildTarget): boolean;
4
+ /** Resolve and bundle dependencies under the selected runtime rules. */
5
+ export declare function resolver(root: string, target: BuildTarget): Bun.BunPlugin;
@@ -0,0 +1,2 @@
1
+ /** Check orb source types before bundling an artifact. */
2
+ export declare function typecheck(entry: string, root: string): void;
@@ -0,0 +1,29 @@
1
+ export declare const Platform: Readonly<{
2
+ readonly Browser: "browser";
3
+ readonly Worker: "worker";
4
+ readonly Node: "node";
5
+ readonly Embedded: "embedded";
6
+ }>;
7
+ export type Platform = (typeof Platform)[keyof typeof Platform];
8
+ export interface BuildTarget {
9
+ entry: string;
10
+ platform: Platform;
11
+ minify?: boolean;
12
+ typecheck?: boolean;
13
+ nativeExternals?: readonly string[];
14
+ define?: Readonly<Record<string, string>>;
15
+ }
16
+ export interface BuildConfig {
17
+ root?: string;
18
+ outDir?: string;
19
+ builds: Readonly<Record<string, BuildTarget>>;
20
+ }
21
+ export interface Artifact {
22
+ name: string;
23
+ platform: Platform;
24
+ path: string;
25
+ sha256: string;
26
+ bytes: number;
27
+ }
28
+ /** Preserve build target types in a tooling configuration. */
29
+ export declare function defineConfig<const C extends BuildConfig>(config: C): C;
@@ -0,0 +1 @@
1
+ export * from "./authoring/types.ts";
@@ -0,0 +1,23 @@
1
+ /** Owned bridge slots. Local values never pass through the metadata kernel or a codec. */
2
+ export declare class Values {
3
+ #private;
4
+ readonly allocate?: (() => number) | undefined;
5
+ /** Use the shared kernel allocator when values cross language adapters. */
6
+ constructor(allocate?: (() => number) | undefined);
7
+ /** Retain a value under a fresh bridge identity. */
8
+ put(value: unknown): number;
9
+ /** Resolve a retained value or reject an expired identity. */
10
+ get<T = unknown>(id: number): T;
11
+ /** Release the value held by one bridge identity. */
12
+ drop(id: number): void;
13
+ /** Check whether this adapter already retains the value. */
14
+ has(id: number): boolean;
15
+ /** Cache a value under an identity issued by another adapter. */
16
+ set(id: number, value: unknown): void;
17
+ /** Release all retained values at host shutdown. */
18
+ clear(): void;
19
+ /** Count the value slots retained by this adapter. */
20
+ get size(): number;
21
+ }
22
+ /** Freezes new plain-data branches once. An externally shallow-frozen value is still traversed. */
23
+ export declare function protect<T>(value: T): Readonly<T>;
package/package.json CHANGED
@@ -1,6 +1,105 @@
1
1
  {
2
2
  "name": "@syntropika/tembra-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "license": "Apache-2.0",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/syntropika/tembra.git",
8
+ "directory": "packages/ts/sdk"
9
+ },
10
+ "files": [
11
+ "src",
12
+ "dist"
13
+ ],
14
+ "type": "module",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./src/index.ts",
18
+ "bun": "./src/index.ts",
19
+ "browser": "./src/index.ts",
20
+ "source": "./src/index.ts",
21
+ "import": "./dist/index.js"
22
+ },
23
+ "./node": {
24
+ "types": "./src/node.ts",
25
+ "bun": "./src/node.ts",
26
+ "browser": "./src/node.ts",
27
+ "source": "./src/node.ts",
28
+ "import": "./dist/node.js"
29
+ },
30
+ "./browser": {
31
+ "types": "./src/browser.ts",
32
+ "bun": "./src/browser.ts",
33
+ "browser": "./src/browser.ts",
34
+ "source": "./src/browser.ts",
35
+ "import": "./dist/browser.js"
36
+ },
37
+ "./runtime": {
38
+ "types": "./src/host.ts",
39
+ "bun": "./src/host.ts",
40
+ "browser": "./src/host.ts",
41
+ "source": "./src/host.ts",
42
+ "import": "./dist/host.js"
43
+ },
44
+ "./tooling": {
45
+ "types": "./src/tooling/index.ts",
46
+ "bun": "./src/tooling/index.ts",
47
+ "browser": "./src/tooling/index.ts",
48
+ "source": "./src/tooling/index.ts",
49
+ "import": "./dist/tooling/index.js"
50
+ },
51
+ "./msgpack": {
52
+ "types": "./src/msgpack.ts",
53
+ "bun": "./src/msgpack.ts",
54
+ "browser": "./src/msgpack.ts",
55
+ "source": "./src/msgpack.ts",
56
+ "import": "./dist/msgpack.js"
57
+ },
58
+ "./coordinator": {
59
+ "types": "./src/coordinator.ts",
60
+ "bun": "./src/coordinator.ts",
61
+ "browser": "./src/coordinator.ts",
62
+ "source": "./src/coordinator.ts",
63
+ "import": "./dist/coordinator.js"
64
+ },
65
+ "./manager": {
66
+ "types": "./src/manager.ts",
67
+ "bun": "./src/manager.ts",
68
+ "browser": "./src/manager.ts",
69
+ "source": "./src/manager.ts",
70
+ "import": "./dist/manager.js"
71
+ },
72
+ "./rpc": {
73
+ "types": "./src/rpc.ts",
74
+ "bun": "./src/rpc.ts",
75
+ "browser": "./src/rpc.ts",
76
+ "source": "./src/rpc.ts",
77
+ "import": "./dist/rpc.js"
78
+ },
79
+ "./telemetry": {
80
+ "types": "./src/telemetry.ts",
81
+ "bun": "./src/telemetry.ts",
82
+ "browser": "./src/telemetry.ts",
83
+ "source": "./src/telemetry.ts",
84
+ "import": "./dist/telemetry.js"
85
+ },
86
+ "./embedded-runtime": "./dist/embedded.js"
87
+ },
88
+ "publishConfig": {
89
+ "access": "public"
90
+ },
91
+ "dependencies": {
92
+ "@syntropika/tembra-engine-node": "0.1.0",
93
+ "@syntropika/tembra-engine-wasm": "0.1.0",
94
+ "enhanced-resolve": "5.26.0",
95
+ "typescript": "5.9.3"
96
+ },
97
+ "optionalDependencies": {
98
+ "@msgpack/msgpack": "3.1.3"
99
+ },
100
+ "engines": {
101
+ "bun": ">=1.4.3",
102
+ "node": ">=22"
103
+ },
104
+ "packageManager": "bun@1.4.3"
105
+ }
@@ -0,0 +1,220 @@
1
+ import { EnvironmentPhase, KernelOp } from "../bridge/protocol.ts";
2
+ import { Errors } from "../errors.ts";
3
+
4
+ import { refuse } from "../error.ts";
5
+ import type { Context } from "../runtime/context.ts";
6
+ import type { Environment } from "../runtime/records.ts";
7
+ import type { Session } from "../runtime/session.ts";
8
+ import type { Readable, State, StateOptions } from "../state.ts";
9
+ import { StateBinding, validate } from "../state.ts";
10
+ import type {
11
+ AcquisitionOptions,
12
+ Completion,
13
+ DynamicReference,
14
+ EventSource,
15
+ ListenerOptions,
16
+ Resource,
17
+ ResourceOptions,
18
+ TaskScope,
19
+ } from "./types.ts";
20
+
21
+ /** Available only during its synchronous factory pass. Issued handles remain usable afterwards. */
22
+ export class Declaration {
23
+ /** Bind declarations to one synchronous factory pass. */
24
+ constructor(
25
+ readonly session: Session,
26
+ readonly environment: Environment,
27
+ ) {}
28
+
29
+ /** Reject declarations after the factory returns. */
30
+ private check(): void {
31
+ if (this.environment.phase !== EnvironmentPhase.Declaring)
32
+ refuse(Errors.Invalid.FactoryExpired, "Declarations must be synchronous");
33
+ }
34
+
35
+ /** Read the identity that owns this scope. */
36
+ get principal(): string {
37
+ return this.session.principalFor(this.environment.object?.id ?? 0);
38
+ }
39
+
40
+ /** Read the shared value created by the orb factory. */
41
+ get orb(): unknown {
42
+ return this.environment.orb.scope?.value;
43
+ }
44
+
45
+ /** Read the object key, or the default key outside an object. */
46
+ get key(): readonly string[] {
47
+ return this.environment.object?.address.key ?? ["main"];
48
+ }
49
+
50
+ /** Declare object state with local validation and versioned migration. */
51
+ state<T>(initial: T, options: StateOptions<T> = {}): State<T> {
52
+ this.check();
53
+ const environment = this.environment;
54
+ const object = environment.object;
55
+ if (!object || environment.state)
56
+ refuse(Errors.Invalid.State, "An object declares exactly one state");
57
+ const version = options.version ?? 1;
58
+ if (!Number.isInteger(version) || version <= 0) refuse(Errors.Invalid.StateVersion);
59
+ let binding = object.binding;
60
+ if (!binding && object.live)
61
+ binding = new StateBinding(this.session, object.id, validate(initial, options));
62
+ if (!binding) {
63
+ const value = validate(initial, options);
64
+ const id = this.session.values.put(value);
65
+ try {
66
+ this.session.kernel.command(KernelOp.StateInit, { object: object.id, value: id, version });
67
+ } catch (error) {
68
+ this.session.values.drop(id);
69
+ throw error;
70
+ }
71
+ object.binding = binding = new StateBinding(this.session, object.id);
72
+ }
73
+ const handle = binding.view(options);
74
+ environment.state = { initial, options, binding };
75
+ return handle;
76
+ }
77
+
78
+ /** Orb factories cannot depend on their own services; object factories may use sibling services. */
79
+ get(
80
+ service: string,
81
+ key: string | readonly string[],
82
+ options: AcquisitionOptions = {},
83
+ ): DynamicReference {
84
+ this.check();
85
+ const requirement = this.session.scopes.requirement(this.environment, service);
86
+ const resolved = requirement.service;
87
+ if (!this.environment.object && this.environment.orb.definition.services?.[resolved])
88
+ refuse(Errors.Invalid.DependencyCycle);
89
+ const identity = JSON.stringify([resolved, key, options.principal ?? this.principal]);
90
+ const existing = this.environment.dependencies.get(identity);
91
+ if (existing) return existing;
92
+ const reference = this.session.handles.hold(resolved, key, {
93
+ ...options,
94
+ ...(requirement.apiVersion ? { apiVersion: requirement.apiVersion } : {}),
95
+ ...(requirement.methods ? { methods: requirement.methods } : {}),
96
+ principal: options.principal ?? this.principal,
97
+ });
98
+ if (this.environment.object) {
99
+ try {
100
+ this.session.kernel.command(KernelOp.Dependency, {
101
+ object: this.environment.object.id,
102
+ reference: this.session.handles.reference(reference).id,
103
+ });
104
+ } catch (error) {
105
+ reference.release();
106
+ throw error;
107
+ }
108
+ }
109
+ this.environment.dependencies.set(identity, reference);
110
+ return reference;
111
+ }
112
+
113
+ /** Declare an owned resource, or access a named host resource. */
114
+ resource<T>(name: string, options?: ResourceOptions<T>): Resource<T> {
115
+ this.check();
116
+ if (!options) return this.session.scopes.hostResource<T>(name);
117
+ if (this.environment.resources.has(name)) refuse(Errors.Invalid.DuplicateResource, name);
118
+ const resource = this.session.resources.declare(this.environment, name, options);
119
+ this.environment.resources.set(name, resource);
120
+ return resource.handle;
121
+ }
122
+
123
+ /** Register work that ends with its declaring scope. */
124
+ task(start: (scope: TaskScope) => Completion<void>): void {
125
+ this.check();
126
+ if (typeof start !== "function") refuse(Errors.Invalid.Task);
127
+ this.environment.tasks.push({ start });
128
+ }
129
+
130
+ /** Declare a bounded listener that starts after activation. */
131
+ on<T>(
132
+ name: string,
133
+ source: EventSource<T> | (() => EventSource<T>),
134
+ handle: (context: Context, value: T) => unknown,
135
+ options: ListenerOptions = {},
136
+ ): void {
137
+ this.check();
138
+ if (!this.session.kernel.features.subscriptions) refuse(Errors.Invalid.SubscriptionsDisabled);
139
+ if (options.maxBytes !== undefined && !options.sizeOf)
140
+ refuse(
141
+ Errors.Invalid.SubscriptionSize,
142
+ "A local byte budget requires an explicit sizeOf function",
143
+ );
144
+ if (!name || this.environment.listeners.some((listener) => listener.name === name))
145
+ refuse(Errors.Invalid.DuplicateListener, name);
146
+ this.environment.listeners.push({ name, source, handle, options });
147
+ }
148
+
149
+ /** Bind a declared hook to this scope. */
150
+ hook(name: string): {
151
+ /** Execute this hook under an issued operation context. */
152
+ run(context: Context, input?: unknown): Promise<unknown>;
153
+ /** Await one observation from this hook's original physical operation, even after cancellation.
154
+ * A successful admission is consumed across all hook handles for that source invocation.
155
+ * The scope retains principal/version, starts with empty metadata, and respects owner/host close.
156
+ * Observer errors reject this promise; the consumer retains its primary outcome separately.
157
+ * A root-only source rejects with forbidden/observation_source without consuming admission.
158
+ * Dependent calls require exact open scopes and registered ancestors; missing scopes reject
159
+ * with gone/scope and closing scopes with conflict/scope_closed. Ordinary calls are unchanged.
160
+ */
161
+ observe(source: Context, input?: unknown): Promise<void>;
162
+ } {
163
+ this.check();
164
+ if (!this.session.kernel.features.hooks) refuse(Errors.Invalid.HooksDisabled);
165
+ if (!this.environment.orb.definition.hooks?.[name]) refuse(Errors.Invalid.Hook, name);
166
+ const operation = this.session.kernel.command<number>(KernelOp.Allocate);
167
+ return {
168
+ /** Require an issued context before entering the declared hook. */
169
+ run: (context, input) => this.session.orbs.runHook(this.environment, name, context, input),
170
+ observe: (source, input) =>
171
+ this.session.orbs.observe(this.environment, name, operation, source, input),
172
+ };
173
+ }
174
+ }
175
+
176
+ /** Expose state reads while the consuming reference remains valid. */
177
+ export function consumerState<T>(
178
+ binding: StateBinding<T>,
179
+ check: () => void,
180
+ cleanups: Set<() => void>,
181
+ ): Readable<T> {
182
+ return {
183
+ /** Read state while the consuming reference remains valid. */
184
+ get value() {
185
+ check();
186
+ return binding.value;
187
+ },
188
+ /** Create a selection tied to this reference's cleanup. */
189
+ select(compute) {
190
+ check();
191
+ return binding.select(compute, check, cleanups);
192
+ },
193
+ /** Detach this observer when the consuming reference is released. */
194
+ subscribe(listener) {
195
+ check();
196
+ const detach = binding.subscribe((value) => {
197
+ try {
198
+ check();
199
+ } catch {
200
+ return;
201
+ }
202
+ listener(value);
203
+ });
204
+ let active = true;
205
+ const cleanup = () => {
206
+ if (!active) return;
207
+ active = false;
208
+ cleanups.delete(cleanup);
209
+ detach();
210
+ };
211
+ cleanups.add(cleanup);
212
+ try {
213
+ check();
214
+ } catch {
215
+ cleanup();
216
+ }
217
+ return cleanup;
218
+ },
219
+ };
220
+ }
@@ -0,0 +1,101 @@
1
+ import { HookCapability } from "../bridge/identifiers.ts";
2
+ import { TembraError } from "../error.ts";
3
+ import { Errors } from "../errors.ts";
4
+ import type { HookDefinition } from "./types.ts";
5
+
6
+ /** Run participants in order with the same input. */
7
+ export function series(): HookDefinition {
8
+ return {
9
+ capabilities: [HookCapability.Observe],
10
+ /** Await each participant before starting the next. */
11
+ async run(ctx, input, participants) {
12
+ for (const participant of participants) await participant(ctx, input);
13
+ },
14
+ };
15
+ }
16
+
17
+ /** Pass each result to the next participant. */
18
+ export function waterfall(): HookDefinition {
19
+ return {
20
+ capabilities: [HookCapability.Transform],
21
+ /** Feed each result into the next participant. */
22
+ async run(ctx, value, participants) {
23
+ for (const participant of participants) value = await participant(ctx, value);
24
+ return value;
25
+ },
26
+ };
27
+ }
28
+
29
+ /** Return the first result that is not undefined. */
30
+ export function bail(): HookDefinition {
31
+ return {
32
+ capabilities: [HookCapability.Decide],
33
+ /** Stop at the first defined result. */
34
+ async run(ctx, value, participants) {
35
+ for (const participant of participants) {
36
+ const result = await participant(ctx, value);
37
+ if (result !== undefined) return result;
38
+ }
39
+ },
40
+ };
41
+ }
42
+
43
+ /** Wait for all participants before returning or failing. */
44
+ export function parallel(): HookDefinition {
45
+ return {
46
+ capabilities: [HookCapability.Observe],
47
+ /** Wait for every participant, including those still running after failure. */
48
+ async run(ctx, value, participants) {
49
+ const settled = await Promise.allSettled(
50
+ participants.map((participant) => participant(ctx, value)),
51
+ );
52
+ const error = settled.find((result) => result.status === "rejected");
53
+ if (error?.status === "rejected") throw error.reason;
54
+ return settled.map((result) => (result.status === "fulfilled" ? result.value : undefined));
55
+ },
56
+ };
57
+ }
58
+
59
+ /** Compose participants with single-use continuations. */
60
+ export function middleware(
61
+ terminal: (context: import("../runtime/context.ts").Context, input: any) => unknown,
62
+ ): HookDefinition {
63
+ return {
64
+ capabilities: [HookCapability.Transform, HookCapability.Decide],
65
+ /** Keep continuations valid only while this hook run remains active. */
66
+ async run(ctx, input, participants) {
67
+ let active = true;
68
+ /** Keep each continuation inside its participant's physical lifetime. */
69
+ async function invoke(index: number, value: unknown): Promise<unknown> {
70
+ if (!active) throw new TembraError(Errors.Expired.Next, "Continuation scope has ended");
71
+ ctx.check();
72
+ const participant = participants[index];
73
+ if (!participant) return terminal(ctx, value);
74
+ let used = false;
75
+ let pending: Promise<unknown> | undefined;
76
+ let open = true;
77
+ const next = (nextValue: unknown) => {
78
+ if (!open || !active) return Promise.reject(new TembraError(Errors.Expired.Next));
79
+ if (used) return Promise.reject(new TembraError(Errors.Invalid.NextUsed));
80
+ used = true;
81
+ pending = invoke(index + 1, nextValue);
82
+ // A caller may catch the rejection normally; no special recovery operation exists.
83
+ pending.catch(() => {});
84
+ return pending;
85
+ };
86
+ try {
87
+ return await participant(ctx, value, next);
88
+ } finally {
89
+ open = false;
90
+ // A detached continuation still owns physical work until it settles.
91
+ if (pending) await pending.catch(() => {});
92
+ }
93
+ }
94
+ try {
95
+ return await invoke(0, input);
96
+ } finally {
97
+ active = false;
98
+ }
99
+ },
100
+ };
101
+ }