@nylorun/core 0.17.0-beta → 0.19.0-beta

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.
@@ -1,16 +1,20 @@
1
1
  /**
2
- * Schemas of the Harness API's frames and payloads. A socket validates every frame it
3
- * receives; the in-process channel does in JSON mode (tests). Engine documents (manifests,
4
- * checkpoints, outcomes) are checked by the engine and the record, not here.
2
+ * Schemas of the Harness API's frames and payloads, and the source of its types (`messages.ts`
3
+ * infers each from its schema). A socket validates every frame it receives; the in-process
4
+ * channel does in JSON mode (tests). Engine documents (manifests, checkpoints, outcomes) are
5
+ * checked by the engine and the record, not here.
5
6
  */
6
7
  import { z } from "zod";
7
8
  import { ABORT_REASONS, HARNESS_API_VERSION, HARNESS_CLAIMS, HARNESS_ERROR_CODES, } from "./messages.js";
8
9
  import { HarnessApiError } from "./errors.js";
10
+ import { EffectOutcomeSchema } from "../contracts.js";
9
11
  import { SANDBOX_TOOL_NAMES } from "../utils/sandbox.js";
10
12
  const id = z.string().min(1).max(512);
11
13
  const runId = z.object({ runId: id });
12
- const outcome = z.object({ value: z.unknown(), statePatch: z.record(z.string(), z.unknown()).optional() }).strict();
13
- const update = z
14
+ /** An engine document (a manifest, a checkpoint): an object here, which the engine checks. */
15
+ const document = z.record(z.string(), z.unknown());
16
+ /** The payload of one `transcript.updated` event. */
17
+ export const TranscriptUpdateSchema = z
14
18
  .object({ keep: z.number().int().min(0), entries: z.array(z.unknown()), length: z.number().int().min(0) })
15
19
  .strict();
16
20
  export const FrameSchema = z.union([
@@ -28,6 +32,7 @@ export const FrameSchema = z.union([
28
32
  z.object({ t: z.literal("abort"), id: z.number().int().positive() }).strict(),
29
33
  z.object({ t: z.literal("ping") }).strict(),
30
34
  ]);
35
+ /** One effect the engine asks for: a `HostEffect`, by structure. Model intents carry no `input`. */
31
36
  export const EffectIntentSchema = z
32
37
  .object({
33
38
  effectId: id,
@@ -46,7 +51,12 @@ export const EffectIntentSchema = z
46
51
  context: z.record(z.string(), z.unknown()),
47
52
  })
48
53
  .strict();
49
- const workspaceRecord = z
54
+ /** A completed outcome of the segment, with the hash of the request it answered. */
55
+ export const RecordedOutcomeSchema = z
56
+ .object({ effectId: id, requestHash: z.string(), outcome: EffectOutcomeSchema })
57
+ .strict();
58
+ /** A workspace's compute record, as the harness keeps it. */
59
+ export const WorkspaceRecordSchema = z
50
60
  .object({
51
61
  key: z.string().min(1).max(512),
52
62
  sessionId: id,
@@ -58,31 +68,51 @@ const workspaceRecord = z
58
68
  updatedAt: z.string(),
59
69
  })
60
70
  .strict();
61
- const workspaceCall = z
71
+ /** The session a workspace request acts for: the workspace's owner and its sandbox resource. */
72
+ export const WorkspaceSessionSchema = z
62
73
  .object({
63
- session: z
64
- .object({ ownerId: id, sandboxId: id.optional(), activeTurnId: id.nullable() })
65
- .strict(),
74
+ /** The session that owns the workspace: its log records the workspace's events. */
75
+ ownerId: id,
76
+ sandboxId: id.optional(),
77
+ activeTurnId: id.nullable(),
78
+ })
79
+ .strict();
80
+ /** A sandbox tool call core sends to the harness that serves workspaces. */
81
+ export const WorkspaceCallSchema = z
82
+ .object({
83
+ session: WorkspaceSessionSchema,
84
+ /** The sandbox spec the workspace runs (`SandboxManifest`). */
66
85
  spec: z.unknown(),
67
86
  tool: z.enum(SANDBOX_TOOL_NAMES),
68
87
  input: z.unknown(),
69
88
  })
70
89
  .strict();
71
- const workspaceBytes = z
90
+ /**
91
+ * A file of a workspace read as bytes (`save_artifact`, F8.1), at most `maxBytes`. The answer is
92
+ * `{kind: "read", path, base64}`, `{kind: "missing", path}` or a failed tool outcome.
93
+ */
94
+ export const WorkspaceBytesCallSchema = z
72
95
  .object({
73
- session: workspaceCall.shape.session,
96
+ session: WorkspaceSessionSchema,
74
97
  spec: z.unknown(),
75
98
  bytes: z.object({ path: z.string().min(1), maxBytes: z.number().int().positive() }).strict(),
76
99
  })
77
100
  .strict();
78
- const workspaceList = z
101
+ /**
102
+ * The regular files under a directory of a workspace, recursively, at most `maxEntries + 1`
103
+ * (the turn-end export, F8.2). The answer is `{kind: "listed", path, listing: {entries,
104
+ * truncated}}`, `{kind: "missing", path}` (no sandbox yet, or not a directory) or a failed tool
105
+ * outcome.
106
+ */
107
+ export const WorkspaceListCallSchema = z
79
108
  .object({
80
- session: workspaceCall.shape.session,
109
+ session: WorkspaceSessionSchema,
81
110
  spec: z.unknown(),
82
111
  list: z.object({ dir: z.string().min(1), maxEntries: z.number().int().positive() }).strict(),
83
112
  })
84
113
  .strict();
85
- const grant = z
114
+ /** The lease on one run. `token` is the run token (F5) when the gates require one. */
115
+ export const RunGrantSchema = z
86
116
  .object({
87
117
  runId: id,
88
118
  sessionId: id,
@@ -92,14 +122,41 @@ const grant = z
92
122
  tokenExpiresAt: z.string().optional(),
93
123
  })
94
124
  .strict();
125
+ /** Where a harness sends the session's tool calls. */
126
+ export const RunRoutingSchema = z
127
+ .object({
128
+ /** The session's pinned manifest: an effect's agent resolves against it. */
129
+ rootManifest: document,
130
+ mcpSnapshot: z.unknown().optional(),
131
+ /** The session that owns the tree's sandbox, and the sandbox resource it is attached to. */
132
+ sandbox: z
133
+ .object({
134
+ ownerId: id,
135
+ sandboxId: id.optional(),
136
+ spec: z.unknown().optional(),
137
+ /**
138
+ * Variables every sandbox command gets (R2c, D50): each `environment_secret` name set to
139
+ * the sentinel `nylorun-managed`, and each `environment_variable`'s value. Never a secret.
140
+ */
141
+ environment: z.record(z.string(), z.string()).optional(),
142
+ })
143
+ .strict()
144
+ .optional(),
145
+ })
146
+ .strict();
147
+ /** What a run starts from: `turn.start` (message, continue, resume) or `approval.answer`. */
95
148
  export const TurnStartSchema = z
96
149
  .object({
97
150
  type: z.enum(["turn.start", "approval.answer"]),
98
151
  engine: z.enum(["agent", "flow"]),
99
- manifest: z.record(z.string(), z.unknown()),
100
- checkpoint: z.record(z.string(), z.unknown()),
101
- sessionTools: z.array(z.unknown()).optional(),
102
- outcomes: z.array(z.object({ effectId: id, requestHash: z.string(), outcome }).strict()),
152
+ /** The turn's manifest (agent) or the workflow manifest (flow). */
153
+ manifest: document,
154
+ /** The segment's checkpoint; an agent's state has no transcript (`transcript.cursor`). */
155
+ checkpoint: document,
156
+ sessionTools: z.array(z.unknown()).readonly().optional(),
157
+ /** Completed outcomes of this segment, resolved without asking core. */
158
+ outcomes: z.array(RecordedOutcomeSchema).readonly(),
159
+ /** The record position the session's transcript was folded at. */
103
160
  transcript: z.object({ cursor: z.number().int() }).strict(),
104
161
  options: z
105
162
  .object({
@@ -108,36 +165,49 @@ export const TurnStartSchema = z
108
165
  fixtureModel: z.boolean(),
109
166
  })
110
167
  .strict(),
111
- routing: z
112
- .object({
113
- rootManifest: z.record(z.string(), z.unknown()),
114
- mcpSnapshot: z.unknown().optional(),
115
- sandbox: z
116
- .object({ ownerId: id, sandboxId: id.optional(), spec: z.unknown().optional() })
117
- .strict()
118
- .optional(),
119
- })
120
- .strict(),
168
+ routing: RunRoutingSchema,
121
169
  })
122
170
  .strict();
171
+ /**
172
+ * A segment's end. `state` is the agent's engine state without its transcript; `transcript`
173
+ * edits the transcript the segment started from. `thrown` reports an engine that threw.
174
+ */
123
175
  export const TurnOutputSchema = z
124
176
  .object({
125
177
  runId: id,
178
+ /** How the segment ended, as the harness reports it. */
126
179
  status: z.enum(["completed", "paused", "yielded", "waiting", "uncertain", "failed", "cancelled"]).optional(),
127
180
  state: z.unknown().optional(),
128
181
  output: z.unknown().optional(),
129
182
  pending: z.unknown().optional(),
130
183
  error: z.unknown().optional(),
131
- effectIds: z.array(z.string()).optional(),
132
- cancelEffectIds: z.array(z.string()).optional(),
133
- transcript: z.array(update).optional(),
184
+ effectIds: z.array(z.string()).readonly().optional(),
185
+ cancelEffectIds: z.array(z.string()).readonly().optional(),
186
+ transcript: z.array(TranscriptUpdateSchema).readonly().optional(),
134
187
  thrown: z.object({ code: z.string().optional(), message: z.string() }).strict().optional(),
135
188
  })
136
189
  .strict();
190
+ /** Why a harness gave a run back without an output. */
191
+ export const ReleaseReasonSchema = z.enum(["shutdown", "ownership.lost", "connection.lost"]);
192
+ export const IntentAnswerSchema = z.union([
193
+ z.object({ status: z.literal("completed"), outcome: EffectOutcomeSchema }).strict(),
194
+ z.object({ status: z.enum(["pending", "uncertain"]) }).strict(),
195
+ z.object({ status: z.literal("execute"), rejoin: z.literal(true).optional() }).strict(),
196
+ ]);
197
+ export const OutcomeAnswerSchema = z.union([
198
+ z.object({ status: z.literal("completed"), outcome: EffectOutcomeSchema }).strict(),
199
+ z.object({ status: z.literal("uncertain") }).strict(),
200
+ ]);
137
201
  const settled = z.object({ cursor: z.number().int().optional() }).strict();
138
202
  const empty = z.object({}).strict();
139
203
  const outcomeObject = z.record(z.string(), z.unknown());
140
- const requests = {
204
+ /** Requests a harness sends to core, with their answers. */
205
+ export const harnessRequests = {
206
+ /**
207
+ * `capabilities.workspace` declares that the harness serves the Tenant's workspaces (F6.2):
208
+ * core then sends it the `workspace.*` requests. The answer names the Tenant (its workspace
209
+ * keys are scoped by it) and the sandbox backend preference the harness selects with.
210
+ */
141
211
  hello: {
142
212
  params: z
143
213
  .object({
@@ -158,7 +228,7 @@ const requests = {
158
228
  },
159
229
  lease: {
160
230
  params: z.object({ slots: z.number().int().positive().optional() }).strict(),
161
- result: z.object({ run: grant, input: TurnStartSchema }).strict(),
231
+ result: z.object({ run: RunGrantSchema, input: TurnStartSchema }).strict(),
162
232
  },
163
233
  "lease.renew": {
164
234
  params: runId.strict(),
@@ -168,26 +238,19 @@ const requests = {
168
238
  ]),
169
239
  },
170
240
  "lease.release": {
171
- params: runId.extend({ reason: z.enum(["shutdown", "ownership.lost", "connection.lost"]) }).strict(),
241
+ params: runId.extend({ reason: ReleaseReasonSchema }).strict(),
172
242
  result: empty,
173
243
  },
174
244
  "effect.intent": {
175
245
  params: runId.extend({ effect: EffectIntentSchema, requestHash: z.string().regex(/^[0-9a-f]{64}$/) }).strict(),
176
- result: z.union([
177
- z.object({ status: z.literal("completed"), outcome }).strict(),
178
- z.object({ status: z.enum(["pending", "uncertain"]) }).strict(),
179
- z.object({ status: z.literal("execute"), rejoin: z.literal(true).optional() }).strict(),
180
- ]),
246
+ result: IntentAnswerSchema,
181
247
  },
182
248
  "effect.outcome": {
183
249
  params: z.union([
184
250
  runId.extend({ effectId: id, value: z.unknown() }).strict(),
185
251
  runId.extend({ effectId: id, error: z.string() }).strict(),
186
252
  ]),
187
- result: z.union([
188
- z.object({ status: z.literal("completed"), outcome }).strict(),
189
- z.object({ status: z.literal("uncertain") }).strict(),
190
- ]),
253
+ result: OutcomeAnswerSchema,
191
254
  },
192
255
  "transcript.read": {
193
256
  params: runId.strict(),
@@ -201,7 +264,8 @@ const requests = {
201
264
  turnId: id.nullable(),
202
265
  type: z.enum(HARNESS_CLAIMS),
203
266
  payload: z.unknown(),
204
- record: workspaceRecord.optional(),
267
+ /** With `sandbox.state`: the workspace's compute record as it is now. */
268
+ record: WorkspaceRecordSchema.optional(),
205
269
  })
206
270
  .strict(),
207
271
  result: empty,
@@ -210,6 +274,10 @@ const requests = {
210
274
  params: runId.extend({ snapshot: z.unknown().optional(), diagnostics: z.array(z.unknown()) }).strict(),
211
275
  result: z.object({ snapshot: z.unknown(), sessionTools: z.array(z.unknown()) }).strict(),
212
276
  },
277
+ /**
278
+ * A definition file's bytes, base64 (track R2 M4): one the run's definition names, for the
279
+ * skills its sandbox mounts.
280
+ */
213
281
  "definition.file": {
214
282
  params: runId.extend({ sha256: z.string().regex(/^sha256:[0-9a-f]{64}$/) }).strict(),
215
283
  result: z.object({ base64: z.string() }).strict(),
@@ -218,15 +286,30 @@ const requests = {
218
286
  "turn.paused": { params: TurnOutputSchema, result: settled },
219
287
  "turn.waiting": { params: TurnOutputSchema, result: settled },
220
288
  "turn.failed": { params: TurnOutputSchema, result: settled },
289
+ /** A yielded segment's state: ends the run, the turn goes on in the next. */
221
290
  checkpoint: { params: TurnOutputSchema, result: settled },
222
- "workspace.read": { params: z.union([workspaceCall, workspaceBytes, workspaceList]), result: outcomeObject },
223
- "workspace.write": { params: workspaceCall, result: outcomeObject },
224
- "workspace.exec": { params: workspaceCall, result: outcomeObject },
291
+ };
292
+ /**
293
+ * Requests core sends to a harness that declared `workspace` (F6.2), with their answers. A
294
+ * sandbox tool's answer is its `SandboxToolOutcome`; the harness claims its `sandbox.*` events
295
+ * while the request is in flight. `workspace.read` stays generic: F8.2 exports outputs
296
+ * through it.
297
+ */
298
+ export const coreRequests = {
299
+ "workspace.read": {
300
+ params: z.union([WorkspaceCallSchema, WorkspaceBytesCallSchema, WorkspaceListCallSchema]),
301
+ result: outcomeObject,
302
+ },
303
+ "workspace.write": { params: WorkspaceCallSchema, result: outcomeObject },
304
+ "workspace.exec": { params: WorkspaceCallSchema, result: outcomeObject },
305
+ /** The harness's sandbox selection report (`GET /v1/tenant/sandbox`, Tenant status). */
225
306
  "workspace.report": { params: empty, result: outcomeObject },
307
+ /** Stops idle workspaces, then lists every workspace the harness keeps. */
226
308
  "workspace.sweep": {
227
309
  params: z.object({ now: z.number().optional() }).strict(),
228
- result: z.object({ workspaces: z.array(workspaceRecord) }).strict(),
310
+ result: z.object({ workspaces: z.array(WorkspaceRecordSchema) }).strict(),
229
311
  },
312
+ /** Deletes workspaces with their files: by key, by sandbox resource, or all of them. */
230
313
  "workspace.remove": {
231
314
  params: z
232
315
  .object({
@@ -238,11 +321,13 @@ const requests = {
238
321
  result: empty,
239
322
  },
240
323
  };
241
- const messages = {
242
- cancel: runId
243
- .extend({ reason: z.enum(ABORT_REASONS), message: z.string().optional() })
244
- .strict(),
324
+ /** Messages core sends to a harness, without an answer. */
325
+ export const coreMessages = {
326
+ /** `message` is core's abort message, which the run's executors see as theirs. */
327
+ cancel: runId.extend({ reason: z.enum(ABORT_REASONS), message: z.string().optional() }).strict(),
245
328
  };
329
+ const requests = { ...harnessRequests, ...coreRequests };
330
+ const messages = coreMessages;
246
331
  function check(schema, value, what) {
247
332
  if (!schema)
248
333
  throw new HarnessApiError("invalid", `Unknown ${what}`);
@@ -3,12 +3,10 @@
3
3
  * `transcript.updated` events, each an edit of the transcript before it. Shared by core, which
4
4
  * records and folds them, and a harness, which computes them and keeps its cache with them.
5
5
  */
6
+ import type { z } from "zod";
7
+ import type { TranscriptUpdateSchema } from "./schema.js";
6
8
  /** The payload of one `transcript.updated` event. */
7
- export interface TranscriptUpdate {
8
- keep: number;
9
- entries: unknown[];
10
- length: number;
11
- }
9
+ export type TranscriptUpdate = z.infer<typeof TranscriptUpdateSchema>;
12
10
  /**
13
11
  * An edit's entries are split so each event stays well under S2's 1 MiB record limit: under
14
12
  * 64 KiB when no entry is larger, as a step with one tool result is once the result fits its
@@ -1,8 +1,3 @@
1
- /**
2
- * Transcript edits (blueprint P0.3): a segment's transcript changes are recorded as
3
- * `transcript.updated` events, each an edit of the transcript before it. Shared by core, which
4
- * records and folds them, and a harness, which computes them and keeps its cache with them.
5
- */
6
1
  /**
7
2
  * An edit's entries are split so each event stays well under S2's 1 MiB record limit: under
8
3
  * 64 KiB when no entry is larger, as a step with one tool result is once the result fits its
@@ -0,0 +1,67 @@
1
+ import { type ProjectCredentialsFile } from "./contracts.js";
2
+ /** The newest Project link format this release reads. */
3
+ export declare const PROJECT_LINK_FORMAT = 3;
4
+ /** The newest Project credentials format this release reads. */
5
+ export declare const PROJECT_CREDENTIALS_FORMAT = 1;
6
+ /**
7
+ * The Nylorun home: `home` when given, else `NYLORUN_HOME`, else `~/.nylorun`. `nylorun`
8
+ * keeps the local Tenants under it (`tenants/<name>/`); `NYLORUN_HOME` there is one Tenant's
9
+ * Host root.
10
+ */
11
+ export declare function nylorunHome(home?: string, env?: Readonly<Record<string, string | undefined>>): string;
12
+ /** A local Tenant's Host root: `~/.nylorun/tenants/<name>/`. */
13
+ export declare function tenantHostRoot(name: string): string;
14
+ /**
15
+ * The Project root: the nearest directory with `.nylorun/` (so a linked Project keeps working
16
+ * from a subdirectory), else the nearest with `package.json`; undefined outside a Project.
17
+ */
18
+ export declare function findProjectRoot(cwd?: string): string | undefined;
19
+ /** The nearest directory with `.nylorun/`, where a Project link would be; undefined without one. */
20
+ export declare function findLinkedProjectRoot(cwd?: string): string | undefined;
21
+ export declare function projectLinkPath(projectRoot: string): string;
22
+ export declare function projectCredentialsPath(projectRoot: string): string;
23
+ /** A Project file that cannot be used: not JSON, not its schema, or a newer format. */
24
+ export declare class ProjectFileError extends Error {
25
+ readonly file: "link" | "credentials";
26
+ readonly reason: "invalid" | "newer";
27
+ readonly path: string;
28
+ constructor(file: "link" | "credentials", reason: "invalid" | "newer", path: string);
29
+ }
30
+ /** The Project link as its readers use it: `tenant` only in format 3, `hostUrl` without a trailing `/`. */
31
+ export interface ProjectLink {
32
+ format: 0 | 1 | 2 | 3;
33
+ /** The local Tenant's name (format 3); absent for an installation that is not local. */
34
+ tenant?: string;
35
+ hostUrl: string;
36
+ hostId: string;
37
+ /** Information only: nothing in a request selects a Tenant. */
38
+ tenantId?: string;
39
+ }
40
+ /** The link at `path`; undefined when there is none. */
41
+ export declare function readProjectLinkFile(path: string): ProjectLink | undefined;
42
+ /** The Project's link (`.nylorun/link.json`); undefined when it has none. */
43
+ export declare function readProjectLink(projectRoot: string): ProjectLink | undefined;
44
+ /** The Project's keys as `credentials.json` holds them, without fields this release ignores. */
45
+ export type ProjectCredentials = Pick<ProjectCredentialsFile, "format" | "applicationKey" | "principalId" | "managementKey" | "managementPrincipalId">;
46
+ /**
47
+ * A credentials file (format 0 or 1): the Project's, or one of the key files `nylorun` keeps in
48
+ * a Host root (`project-credentials.json`, `cli-credentials.json`). Undefined when there is
49
+ * none. A format 0 file's legacy `executors` map is ignored.
50
+ */
51
+ export declare function readCredentialsFile(path: string): ProjectCredentials | undefined;
52
+ /** The Project's credentials (`.nylorun/credentials.json`); undefined when it has none. */
53
+ export declare function readProjectCredentials(projectRoot: string): ProjectCredentials | undefined;
54
+ /** The linked Project found from `cwd`: its root and link, and its credentials when it has them. */
55
+ export interface LinkedProject {
56
+ root: string;
57
+ linkPath: string;
58
+ link: ProjectLink;
59
+ credentials?: ProjectCredentials;
60
+ }
61
+ /**
62
+ * The one resolver: the Project from `cwd` upwards (`findLinkedProjectRoot`) and its link and
63
+ * credentials. Undefined when no Project there has a link; a broken file throws
64
+ * `ProjectFileError`. The caller decides what an older link format or missing credentials
65
+ * mean.
66
+ */
67
+ export declare function findLinkedProject(cwd?: string): LinkedProject | undefined;
@@ -0,0 +1,210 @@
1
+ /**
2
+ * The local machine's Nylorun files, for Node clients (`@nylorun/core/project`): the Nylorun
3
+ * home and a local Tenant's Host root, the Project root, and the Project link
4
+ * (`.nylorun/link.json`) and credentials (`.nylorun/credentials.json`) that `nylorun start`
5
+ * writes. It imports `node:fs`, so no browser entry point imports it.
6
+ *
7
+ * Every reader of the link uses it (`@nylorun/agents`, `@nylorun/admin`, `nylorun` and `nylo`),
8
+ * with one behaviour:
9
+ *
10
+ * - The Project is the nearest directory, from the working directory upwards, that holds
11
+ * `.nylorun/`; without one, `findProjectRoot` falls back to the nearest `package.json`. The
12
+ * walk never reaches the home directory, whose `.nylorun/` is the Nylorun home and never a
13
+ * Project, nor anything above it; outside the home directory it ends at the filesystem root.
14
+ * - Reads are synchronous (`createAdmin` resolves synchronously).
15
+ * - A missing file reads as `undefined`. A file that is not JSON or fails its schema
16
+ * (`ProjectLinkFileSchema`, `ProjectCredentialsFileSchema`) throws `ProjectFileError`
17
+ * (`reason: "invalid"`); a newer format than this release reads throws it with
18
+ * `reason: "newer"`. Links of formats 0 to 2 read as such: `nylorun start` replaces them, and
19
+ * the clients refuse them.
20
+ * - Credentials come only from the Project's own `credentials.json`. Falling back to the Host
21
+ * root (`host.json` and its key files) is the Management API's local-Host step
22
+ * (`@nylorun/admin`), never the Runtime API's: an application gets its key from its Project
23
+ * or its environment.
24
+ */
25
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
26
+ import { homedir } from "node:os";
27
+ import { dirname, join, parse, resolve } from "node:path";
28
+ import { ProjectCredentialsFileSchema, ProjectLinkFileSchema, } from "./contracts.js";
29
+ /** The newest Project link format this release reads. */
30
+ export const PROJECT_LINK_FORMAT = 3;
31
+ /** The newest Project credentials format this release reads. */
32
+ export const PROJECT_CREDENTIALS_FORMAT = 1;
33
+ /**
34
+ * The Nylorun home: `home` when given, else `NYLORUN_HOME`, else `~/.nylorun`. `nylorun`
35
+ * keeps the local Tenants under it (`tenants/<name>/`); `NYLORUN_HOME` there is one Tenant's
36
+ * Host root.
37
+ */
38
+ export function nylorunHome(home, env = process.env) {
39
+ if (home !== undefined && home.trim() !== "")
40
+ return resolve(home);
41
+ const fromEnv = env.NYLORUN_HOME?.trim();
42
+ if (fromEnv)
43
+ return resolve(fromEnv);
44
+ return resolve(join(homedir(), ".nylorun"));
45
+ }
46
+ /** A local Tenant's Host root: `~/.nylorun/tenants/<name>/`. */
47
+ export function tenantHostRoot(name) {
48
+ return resolve(join(homedir(), ".nylorun", "tenants", name));
49
+ }
50
+ function real(path) {
51
+ try {
52
+ return realpathSync(path);
53
+ }
54
+ catch {
55
+ return path;
56
+ }
57
+ }
58
+ /** The walk from `cwd` upwards: the nearest `.nylorun/` and the nearest `package.json`. */
59
+ function walk(cwd) {
60
+ const stop = real(homedir());
61
+ let directory = real(resolve(cwd));
62
+ const root = parse(directory).root;
63
+ let packageRoot;
64
+ for (;;) {
65
+ // The home directory is never a Project, but a directory below it is.
66
+ if (directory === stop)
67
+ break;
68
+ if (existsSync(join(directory, ".nylorun")))
69
+ return { linked: directory };
70
+ if (!packageRoot && existsSync(join(directory, "package.json")))
71
+ packageRoot = directory;
72
+ if (directory === root)
73
+ break;
74
+ const parent = dirname(directory);
75
+ if (parent === directory)
76
+ break;
77
+ directory = parent;
78
+ }
79
+ return packageRoot ? { packageRoot } : {};
80
+ }
81
+ /**
82
+ * The Project root: the nearest directory with `.nylorun/` (so a linked Project keeps working
83
+ * from a subdirectory), else the nearest with `package.json`; undefined outside a Project.
84
+ */
85
+ export function findProjectRoot(cwd = process.cwd()) {
86
+ const { linked, packageRoot } = walk(cwd);
87
+ return linked ?? packageRoot;
88
+ }
89
+ /** The nearest directory with `.nylorun/`, where a Project link would be; undefined without one. */
90
+ export function findLinkedProjectRoot(cwd = process.cwd()) {
91
+ return walk(cwd).linked;
92
+ }
93
+ export function projectLinkPath(projectRoot) {
94
+ return join(projectRoot, ".nylorun", "link.json");
95
+ }
96
+ export function projectCredentialsPath(projectRoot) {
97
+ return join(projectRoot, ".nylorun", "credentials.json");
98
+ }
99
+ /** A Project file that cannot be used: not JSON, not its schema, or a newer format. */
100
+ export class ProjectFileError extends Error {
101
+ file;
102
+ reason;
103
+ path;
104
+ constructor(file, reason, path) {
105
+ super(reason === "newer"
106
+ ? `The Project ${file === "link" ? "link" : "credentials"} at ${path} ${file === "link" ? "has" : "have"} a newer format than this release reads. Upgrade this client.`
107
+ : `Invalid Project ${file === "link" ? "link" : "credentials"} at ${path}. Remove .nylorun/${file === "link" ? "link" : "credentials"}.json and run "npx nylorun start".`);
108
+ this.file = file;
109
+ this.reason = reason;
110
+ this.path = path;
111
+ this.name = "ProjectFileError";
112
+ }
113
+ }
114
+ function readText(path) {
115
+ try {
116
+ return readFileSync(path, "utf8");
117
+ }
118
+ catch (error) {
119
+ if (error.code === "ENOENT")
120
+ return undefined;
121
+ throw error;
122
+ }
123
+ }
124
+ function json(text) {
125
+ try {
126
+ return JSON.parse(text);
127
+ }
128
+ catch {
129
+ return undefined;
130
+ }
131
+ }
132
+ function newerFormat(value, newest) {
133
+ const format = value?.format;
134
+ return typeof format === "number" && Number.isInteger(format) && format > newest;
135
+ }
136
+ /** The link at `path`; undefined when there is none. */
137
+ export function readProjectLinkFile(path) {
138
+ const text = readText(path);
139
+ if (text === undefined)
140
+ return undefined;
141
+ const value = json(text);
142
+ if (newerFormat(value, PROJECT_LINK_FORMAT))
143
+ throw new ProjectFileError("link", "newer", path);
144
+ const parsed = ProjectLinkFileSchema.safeParse(value);
145
+ if (!parsed.success)
146
+ throw new ProjectFileError("link", "invalid", path);
147
+ const link = parsed.data;
148
+ return {
149
+ format: link.format,
150
+ ...(link.format === 3 && link.tenant ? { tenant: link.tenant } : {}),
151
+ hostUrl: link.hostUrl.replace(/\/$/, ""),
152
+ hostId: link.hostId,
153
+ ...(link.tenantId ? { tenantId: link.tenantId } : {}),
154
+ };
155
+ }
156
+ /** The Project's link (`.nylorun/link.json`); undefined when it has none. */
157
+ export function readProjectLink(projectRoot) {
158
+ return readProjectLinkFile(projectLinkPath(projectRoot));
159
+ }
160
+ /**
161
+ * A credentials file (format 0 or 1): the Project's, or one of the key files `nylorun` keeps in
162
+ * a Host root (`project-credentials.json`, `cli-credentials.json`). Undefined when there is
163
+ * none. A format 0 file's legacy `executors` map is ignored.
164
+ */
165
+ export function readCredentialsFile(path) {
166
+ const text = readText(path);
167
+ if (text === undefined)
168
+ return undefined;
169
+ const value = json(text);
170
+ if (newerFormat(value, PROJECT_CREDENTIALS_FORMAT))
171
+ throw new ProjectFileError("credentials", "newer", path);
172
+ const parsed = ProjectCredentialsFileSchema.safeParse(value);
173
+ if (!parsed.success)
174
+ throw new ProjectFileError("credentials", "invalid", path);
175
+ const credentials = parsed.data;
176
+ return {
177
+ format: credentials.format,
178
+ applicationKey: credentials.applicationKey,
179
+ principalId: credentials.principalId,
180
+ ...(credentials.managementKey ? { managementKey: credentials.managementKey } : {}),
181
+ ...(credentials.managementPrincipalId
182
+ ? { managementPrincipalId: credentials.managementPrincipalId }
183
+ : {}),
184
+ };
185
+ }
186
+ /** The Project's credentials (`.nylorun/credentials.json`); undefined when it has none. */
187
+ export function readProjectCredentials(projectRoot) {
188
+ return readCredentialsFile(projectCredentialsPath(projectRoot));
189
+ }
190
+ /**
191
+ * The one resolver: the Project from `cwd` upwards (`findLinkedProjectRoot`) and its link and
192
+ * credentials. Undefined when no Project there has a link; a broken file throws
193
+ * `ProjectFileError`. The caller decides what an older link format or missing credentials
194
+ * mean.
195
+ */
196
+ export function findLinkedProject(cwd = process.cwd()) {
197
+ const root = findLinkedProjectRoot(cwd);
198
+ if (root === undefined)
199
+ return undefined;
200
+ const link = readProjectLink(root);
201
+ if (link === undefined)
202
+ return undefined;
203
+ const credentials = link.format === PROJECT_LINK_FORMAT ? readProjectCredentials(root) : undefined;
204
+ return {
205
+ root,
206
+ linkPath: projectLinkPath(root),
207
+ link,
208
+ ...(credentials ? { credentials } : {}),
209
+ };
210
+ }