@tsplc/agent 0.2.17 → 0.2.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/login.ts ADDED
@@ -0,0 +1,238 @@
1
+ import { setTimeout as delay } from "node:timers/promises";
2
+ import {
3
+ type ControllerLogin,
4
+ failureReason,
5
+ findControllerLogin,
6
+ type LoginCommand,
7
+ openControllerLogin,
8
+ } from "@tsplc/build";
9
+ import { LoginUnavailable, noLogin } from "@tsplc/debug";
10
+ import {
11
+ controllerConfig,
12
+ ensureGateway,
13
+ loginContainer,
14
+ withCredentials,
15
+ } from "./codesys";
16
+ import { AgentError, errorMessage } from "./errors";
17
+ import { controllerCredentials } from "./secrets";
18
+ import { appendJsonl } from "./logs";
19
+ import type { Operations } from "./operations";
20
+ import type {
21
+ AgentStatus,
22
+ Audit,
23
+ ClientIdentity,
24
+ Credentials,
25
+ } from "./protocol";
26
+ import type { AgentState } from "./state";
27
+
28
+ /** A login's state comes back within a second; one that takes this long waits on a hung worker. */
29
+ const loginStateTimeout = 30_000;
30
+ const stoppedAnswering = { error: "The login stopped answering" };
31
+
32
+ /** How an audited login command reads in the log, or nothing for commands that only read. */
33
+ const auditOf = (command: LoginCommand) => {
34
+ switch (command.command) {
35
+ case "write":
36
+ case "force":
37
+ return { command: command.command, values: command.values };
38
+ case "unforce":
39
+ return {
40
+ command: command.restore ? "unforce --restore" : "unforce",
41
+ values: Object.fromEntries(
42
+ command.expressions.map((expression) => [expression, ""]),
43
+ ),
44
+ };
45
+ case "start":
46
+ case "stop":
47
+ return { command: command.command, values: {} };
48
+ case "reset":
49
+ return { command: `reset ${command.kind.toLowerCase()}`, values: {} };
50
+ case "state":
51
+ case "read":
52
+ return undefined;
53
+ }
54
+ };
55
+
56
+ /**
57
+ * The agent's engineering login to the controller, which outlives the agent in its own
58
+ * container. Its commands, the debugger's reads among them, run one at a time.
59
+ */
60
+ export const createLogin = (context: {
61
+ state: AgentState;
62
+ operations: Operations;
63
+ /** Called with each audited command once it is in the audit log. */
64
+ onAudit: (entry: Audit) => Promise<void>;
65
+ log: (message: string) => void;
66
+ }) => {
67
+ const { state, operations } = context;
68
+ let generation = 0;
69
+ let commands: Promise<unknown> = Promise.resolve();
70
+
71
+ const enqueue = <Result>(run: () => Promise<Result>) => {
72
+ const queuedIn = generation;
73
+ const sent = commands.then(() => {
74
+ if (queuedIn !== generation) {
75
+ throw new AgentError("The login was closed", 409);
76
+ }
77
+ return run();
78
+ });
79
+ commands = sent.catch(() => undefined);
80
+ return sent;
81
+ };
82
+ const send = (login: ControllerLogin, command: LoginCommand) =>
83
+ enqueue(() => login.send(command));
84
+
85
+ const requireLogin = async () => {
86
+ operations.requireIdle();
87
+ const lookedUpIn = generation;
88
+ const login = await findControllerLogin(loginContainer);
89
+ if (lookedUpIn !== generation) {
90
+ throw new AgentError("The login was closed", 409);
91
+ }
92
+ operations.requireIdle();
93
+ if (!login) {
94
+ throw new AgentError("No login is open: tsplc login", 409);
95
+ }
96
+ return login;
97
+ };
98
+
99
+ return {
100
+ /** What the debugger reads through: the open login, which it never opens itself. */
101
+ read: async ([first, ...rest]: string[]) => {
102
+ const busy = operations.busy();
103
+ if (busy === "a login") {
104
+ throw new LoginUnavailable("The engineering login is opening", {
105
+ state: "connecting",
106
+ });
107
+ }
108
+ if (busy) {
109
+ throw new LoginUnavailable(`Live values pause during ${busy}`);
110
+ }
111
+ const login = await findControllerLogin(loginContainer);
112
+ if (!login) {
113
+ throw new LoginUnavailable(noLogin);
114
+ }
115
+ if (!first) {
116
+ return {};
117
+ }
118
+ const result = await send(login, {
119
+ command: "read",
120
+ expressions: [first, ...rest],
121
+ });
122
+ if (!("values" in result)) {
123
+ throw new Error("The login answered a read without values");
124
+ }
125
+ return result.values;
126
+ },
127
+
128
+ open: async (sent: Credentials | null) => {
129
+ const credentials = await controllerCredentials(sent);
130
+ context.log(
131
+ `Opening a login with the ${sent ? "provided" : "stored"} controller user`,
132
+ );
133
+ const config = controllerConfig(
134
+ await state.requireRelease(),
135
+ await state.requireTarget(),
136
+ state.paths.controller,
137
+ );
138
+ return operations.stream("a login", async (emit) => {
139
+ if (await findControllerLogin(loginContainer)) {
140
+ throw new AgentError("A login is already open", 409);
141
+ }
142
+ emit({
143
+ kind: "progress",
144
+ message: "Logging in; CODESYS takes minutes to start",
145
+ });
146
+ await ensureGateway();
147
+ const login = await withCredentials(credentials, () =>
148
+ openControllerLogin(config, loginContainer),
149
+ );
150
+ return send(login, { command: "state" });
151
+ });
152
+ },
153
+
154
+ /** Runs a login command; one that changes the controller goes to the audit log, with the values it replaces. */
155
+ command: async (command: LoginCommand, client: ClientIdentity) => {
156
+ const login = await requireLogin();
157
+ const change = auditOf(command);
158
+ if (!change) {
159
+ return send(login, command);
160
+ }
161
+ return enqueue(async () => {
162
+ const [first, ...rest] = Object.keys(change.values);
163
+ // Without the old values the command is still worth running and recording.
164
+ const previous = first
165
+ ? await login
166
+ .send({ command: "read", expressions: [first, ...rest] })
167
+ .then((result) =>
168
+ "values" in result ? result.values : undefined,
169
+ )
170
+ .catch(() => undefined)
171
+ : undefined;
172
+ const audit = async (error?: unknown) => {
173
+ const entry: Audit = {
174
+ at: new Date().toISOString(),
175
+ ...change,
176
+ ...(previous && { previous }),
177
+ ...client,
178
+ release: (await state.release())?.id,
179
+ ...(error !== undefined && { error: errorMessage(error) }),
180
+ };
181
+ await appendJsonl(state.paths.audit, entry);
182
+ await context.onAudit(entry);
183
+ };
184
+ try {
185
+ const result = await login.send(command);
186
+ await audit();
187
+ return result;
188
+ } catch (error) {
189
+ await audit(error);
190
+ throw error;
191
+ }
192
+ });
193
+ },
194
+
195
+ /**
196
+ * The open login's state. A login that lost the controller, or whose worker died or hangs, is
197
+ * reported as failed, so the CLI can log it out and open a new one.
198
+ */
199
+ status: async (): Promise<AgentStatus["login"]> => {
200
+ const login = await findControllerLogin(loginContainer);
201
+ if (!login) {
202
+ return null;
203
+ }
204
+ // A login still opening has its container but doesn't answer yet.
205
+ if (!(await login.ready())) {
206
+ return operations.busy() === "a login" ? null : stoppedAnswering;
207
+ }
208
+ try {
209
+ const loginState = await Promise.race([
210
+ send(login, { command: "state" }),
211
+ delay(loginStateTimeout, null),
212
+ ]);
213
+ if (!loginState) {
214
+ return stoppedAnswering;
215
+ }
216
+ return "state" in loginState ? loginState : null;
217
+ } catch (error) {
218
+ return { error: failureReason(error) };
219
+ }
220
+ },
221
+
222
+ /** Logs out, cancelling queued commands; a replacement login starts with an empty queue. */
223
+ logout: async () => {
224
+ const login = await requireLogin();
225
+ return operations.exclusive("a logout", async () => {
226
+ generation++;
227
+ const failure = await login.close();
228
+ commands = Promise.resolve();
229
+ if (failure) {
230
+ context.log(
231
+ `The login couldn't log out (${failure}); its container was removed`,
232
+ );
233
+ }
234
+ return failure ? { failure } : {};
235
+ });
236
+ },
237
+ };
238
+ };
package/src/logs.ts CHANGED
@@ -7,33 +7,43 @@ const rotateBytes = 5 * 2 ** 20;
7
7
 
8
8
  /** Appends one JSON line to an append-only log, keeping it and its rotated copy bounded. */
9
9
  export const appendJsonl = async (file: string, value: unknown) => {
10
- if (existsSync(file) && (await stat(file)).size >= rotateBytes) await rename(file, `${file}.1`);
11
- const log = await open(file, "a+");
12
- try {
13
- const { size } = await log.stat();
14
- const last = Buffer.alloc(1);
15
- if (size) await log.read(last, 0, 1, size - 1);
16
- // A crash may leave a partial line; keep the next complete entry separate from it.
17
- const separator = size && last[0] !== 10 ? "\n" : "";
18
- await log.writeFile(`${separator}${JSON.stringify(value)}\n`);
19
- } finally {
20
- await log.close();
21
- }
10
+ if (existsSync(file) && (await stat(file)).size >= rotateBytes) {
11
+ await rename(file, `${file}.1`);
12
+ }
13
+ const log = await open(file, "a+");
14
+ try {
15
+ const { size } = await log.stat();
16
+ const last = Buffer.alloc(1);
17
+ if (size) {
18
+ await log.read(last, 0, 1, size - 1);
19
+ }
20
+ // A crash may leave a partial line; keep the next complete entry separate from it.
21
+ const separator = size && last[0] !== 10 ? "\n" : "";
22
+ await log.writeFile(`${separator}${JSON.stringify(value)}\n`);
23
+ } finally {
24
+ await log.close();
25
+ }
22
26
  };
23
27
 
24
28
  /** The newest `limit` lines of a log, oldest first. */
25
- export const readJsonl = async <T>(file: string, schema: z.ZodType<T>, limit: number) => {
26
- if (!existsSync(file)) return [];
27
- return (await readFile(file, "utf8"))
28
- .split("\n")
29
- .filter(Boolean)
30
- .slice(-limit)
31
- .flatMap((line) => {
32
- // A crash can leave the last line half written; it is skipped.
33
- try {
34
- return [schema.parse(JSON.parse(line))];
35
- } catch {
36
- return [];
37
- }
38
- });
29
+ export const readJsonl = async <T>(
30
+ file: string,
31
+ schema: z.ZodType<T>,
32
+ limit: number,
33
+ ) => {
34
+ if (!existsSync(file)) {
35
+ return [];
36
+ }
37
+ return (await readFile(file, "utf8"))
38
+ .split("\n")
39
+ .filter(Boolean)
40
+ .slice(-limit)
41
+ .flatMap((line) => {
42
+ // A crash can leave the last line half written; it is skipped.
43
+ try {
44
+ return [schema.parse(JSON.parse(line))];
45
+ } catch {
46
+ return [];
47
+ }
48
+ });
39
49
  };
@@ -0,0 +1,87 @@
1
+ import { explicitDownload } from "@tsplc/build";
2
+ import { AgentError, errorMessage } from "./errors";
3
+ import type { AgentEvent } from "./protocol";
4
+
5
+ /** What the agent can be busy with, as its messages name it. */
6
+ export type Operation = "a deployment" | "a login" | "a logout";
7
+
8
+ /** The agent runs one deployment, login or logout at a time. */
9
+ export const createOperations = (log: (message: string) => void) => {
10
+ let busy: Operation | undefined;
11
+
12
+ const requireIdle = () => {
13
+ if (busy) {
14
+ throw new AgentError(`The agent is busy with ${busy}`, 409);
15
+ }
16
+ };
17
+
18
+ return {
19
+ busy: () => busy,
20
+ requireIdle,
21
+ /** Runs `run` as the agent's one operation. */
22
+ exclusive: async <Result>(
23
+ operation: Operation,
24
+ run: () => Promise<Result>,
25
+ ) => {
26
+ requireIdle();
27
+ busy = operation;
28
+ try {
29
+ return await run();
30
+ } finally {
31
+ busy = undefined;
32
+ }
33
+ },
34
+ /** Streams one exclusive operation's events, then its result, as newline-delimited JSON. */
35
+ stream: (
36
+ operation: Operation,
37
+ run: (emit: (event: AgentEvent) => void) => Promise<unknown>,
38
+ ) => {
39
+ requireIdle();
40
+ busy = operation;
41
+ const encoder = new TextEncoder();
42
+ // A client that disconnects doesn't stop the operation; it just stops hearing about it.
43
+ let listening = true;
44
+ return new Response(
45
+ new ReadableStream({
46
+ start: async (controller) => {
47
+ const write = (text: string) => {
48
+ if (listening) {
49
+ controller.enqueue(encoder.encode(text));
50
+ }
51
+ };
52
+ const emit = (event: AgentEvent) =>
53
+ write(`${JSON.stringify(event)}\n`);
54
+ // CODESYS can stay silent for minutes; blank lines keep proxies from closing the stream.
55
+ const heartbeat = setInterval(() => write("\n"), 15_000);
56
+ try {
57
+ emit({ kind: "done", result: await run(emit) });
58
+ } catch (error) {
59
+ log(
60
+ `${operation} failed: ${error instanceof Error ? error.stack : String(error)}`,
61
+ );
62
+ emit({
63
+ kind: "error",
64
+ message: errorMessage(error),
65
+ downloadRequired:
66
+ (error instanceof AgentError && error.downloadRequired) ||
67
+ (error instanceof Error &&
68
+ error.message.includes(explicitDownload)),
69
+ });
70
+ } finally {
71
+ clearInterval(heartbeat);
72
+ busy = undefined;
73
+ if (listening) {
74
+ controller.close();
75
+ }
76
+ }
77
+ },
78
+ cancel: () => {
79
+ listening = false;
80
+ },
81
+ }),
82
+ { headers: { "Content-Type": "application/x-ndjson" } },
83
+ );
84
+ },
85
+ };
86
+ };
87
+ export type Operations = ReturnType<typeof createOperations>;
package/src/protocol.ts CHANGED
@@ -1,37 +1,47 @@
1
1
  import { tsplcConfigSchema } from "@tsplc/config";
2
+ import { tcpPort } from "@tsplc/config/build";
2
3
  import { z } from "zod";
3
4
 
4
5
  /** The controller the agent deploys to, as its runtime's TCP block driver address. */
5
6
  export const targetSchema = z.strictObject({
6
- host: z.string().nonempty(),
7
- port: z.number().int().min(1).max(65535),
7
+ host: z.string().nonempty(),
8
+ port: tcpPort,
8
9
  });
9
10
  export type Target = z.infer<typeof targetSchema>;
10
11
 
11
12
  export const networkInterfaceSchema = z.strictObject({
12
- name: z.string(),
13
- address: z.ipv4(),
14
- prefixLength: z.number().int().min(0).max(32),
13
+ name: z.string(),
14
+ address: z.ipv4(),
15
+ prefixLength: z.number().int().min(0).max(32),
15
16
  });
16
17
  export type NetworkInterface = z.infer<typeof networkInterfaceSchema>;
17
18
 
18
19
  /** A host on the scanned subnet that accepts connections on the CODESYS runtime port. */
19
20
  export const controllerSchema = z.strictObject({
20
- address: z.ipv4(),
21
- port: z.number().int(),
22
- hostname: z.string().nullable(),
21
+ address: z.ipv4(),
22
+ port: z.number().int(),
23
+ hostname: z.string().nullable(),
23
24
  });
24
25
  export type DiscoveredController = z.infer<typeof controllerSchema>;
25
26
 
26
- /** The controller's user; the agent passes it to CODESYS for one operation and never stores it. */
27
+ /** `POST /discover`: the network interface to scan for controllers. */
28
+ export const discoverSchema = z.strictObject({ name: z.string() });
29
+
30
+ /**
31
+ * The controller's user, which the agent passes to CODESYS for one operation. A request sends
32
+ * null instead to use the one stored on the agent's PC.
33
+ */
27
34
  export const credentialsSchema = z.strictObject({
28
- username: z.string().nonempty(),
29
- password: z.string().nonempty(),
35
+ username: z.string().nonempty(),
36
+ password: z.string().nonempty(),
30
37
  });
31
38
  export type Credentials = z.infer<typeof credentialsSchema>;
32
39
 
33
40
  /** A published leaf of the deployed program, as CODESYS expressions name it. */
34
- export const variableSchema = z.strictObject({ path: z.string(), type: z.string() });
41
+ export const variableSchema = z.strictObject({
42
+ path: z.string(),
43
+ type: z.string(),
44
+ });
35
45
  export type Variable = z.infer<typeof variableSchema>;
36
46
 
37
47
  /**
@@ -39,62 +49,78 @@ export type Variable = z.infer<typeof variableSchema>;
39
49
  * relative to the release: `st/`, `template.project` and `libraries/`.
40
50
  */
41
51
  export const releaseManifestSchema = z.strictObject({
42
- config: z.record(z.string(), z.unknown()),
43
- variables: z.array(variableSchema),
44
- /** The server executable's path in the release, when the project builds one. */
45
- server: z.string().nonempty().optional(),
46
- /** The project's `debug` section; the program's debug manifest is the release's `debug.json`. */
47
- debug: tsplcConfigSchema.shape.debug,
48
- /** The variable in the agent's environment holding the server's bearer token, for its telemetry and request trace. */
49
- serverTokenEnv: z.string().nonempty().optional(),
52
+ config: z.record(z.string(), z.unknown()),
53
+ variables: z.array(variableSchema),
54
+ /** The server executable's path in the release, when the project builds one. */
55
+ server: z.string().nonempty().optional(),
56
+ /** The project's `debug` section; the program's debug manifest is the release's `debug.json`. */
57
+ debug: tsplcConfigSchema.shape.debug,
58
+ /** The variable in the agent's environment holding the server's bearer token, for its telemetry and request trace. */
59
+ serverTokenEnv: z.string().nonempty().optional(),
60
+ /** The project's `secrets`, whose placeholders in the ST the agent fills in from Bun.secrets. */
61
+ secrets: tsplcConfigSchema.shape.secrets,
50
62
  });
51
63
  export type ReleaseManifest = z.infer<typeof releaseManifestSchema>;
52
64
 
53
65
  /** How `tsplc deploy` compresses each uploaded file. */
54
66
  export const uploadEncoding = "gzip";
55
67
 
56
- export const deployOptionsSchema = z.strictObject({
57
- credentials: credentialsSchema,
58
- /** A full download stops the application; without it only an online change is applied. */
59
- download: z.boolean(),
60
- initializeUser: z.boolean(),
61
- });
68
+ export const deployOptionsSchema = z
69
+ .strictObject({
70
+ credentials: credentialsSchema.nullable(),
71
+ /** A full download stops the application; without it only an online change is applied. */
72
+ download: z.boolean(),
73
+ initializeUser: z.boolean(),
74
+ })
75
+ .refine(
76
+ (options) => options.credentials || !options.initializeUser,
77
+ "Initializing the controller's user needs the user's credentials.",
78
+ );
62
79
  export type DeployOptions = z.infer<typeof deployOptionsSchema>;
63
80
 
64
81
  /** Long operations stream one of these per line. */
65
82
  export const eventSchema = z.discriminatedUnion("kind", [
66
- z.strictObject({ kind: z.literal("progress"), message: z.string() }),
67
- z.strictObject({ kind: z.literal("done"), result: z.unknown() }),
68
- z.strictObject({
69
- kind: z.literal("error"),
70
- message: z.string(),
71
- /** The controller has no application from this agent yet, so only a full download can deploy. */
72
- downloadRequired: z.boolean(),
73
- }),
83
+ z.strictObject({ kind: z.literal("progress"), message: z.string() }),
84
+ z.strictObject({ kind: z.literal("done"), result: z.unknown() }),
85
+ z.strictObject({
86
+ kind: z.literal("error"),
87
+ message: z.string(),
88
+ /** The controller has no application from this agent yet, so only a full download can deploy. */
89
+ downloadRequired: z.boolean(),
90
+ }),
74
91
  ]);
75
92
  export type AgentEvent = z.infer<typeof eventSchema>;
76
93
 
94
+ /** A failed request's body. */
95
+ export const errorSchema = z.object({ error: z.string() });
96
+
97
+ const deployOperationSchema = z.enum(["download", "online-change"]);
98
+
77
99
  export const releaseSchema = z.strictObject({
78
- id: z.string(),
79
- deployedAt: z.iso.datetime(),
80
- operation: z.enum(["download", "online-change"]),
81
- controllerIds: z.strictObject({ codeId: z.string(), dataId: z.string() }),
82
- /** The running server executable, relative to the releases directory. */
83
- server: z.string().optional(),
100
+ id: z.string(),
101
+ deployedAt: z.iso.datetime(),
102
+ operation: deployOperationSchema,
103
+ controllerIds: z.strictObject({ codeId: z.string(), dataId: z.string() }),
104
+ /** The running server executable, relative to the releases directory. */
105
+ server: z.string().optional(),
84
106
  });
85
107
  export type Release = z.infer<typeof releaseSchema>;
86
108
 
87
109
  export const statusSchema = z.strictObject({
88
- target: targetSchema.nullable(),
89
- release: releaseSchema.nullable(),
90
- server: z.strictObject({ executable: z.string(), running: z.boolean() }).nullable(),
91
- /** The open login's application state and forced expressions, or why it can't report them. */
92
- login: z
93
- .union([
94
- z.strictObject({ state: z.string(), forced: z.array(z.string()) }),
95
- z.strictObject({ error: z.string() }),
96
- ])
97
- .nullable(),
110
+ target: targetSchema.nullable(),
111
+ release: releaseSchema.nullable(),
112
+ server: z
113
+ .strictObject({ executable: z.string(), running: z.boolean() })
114
+ .nullable(),
115
+ /** The open login's application state and forced expressions, or why it can't report them. */
116
+ login: z
117
+ .union([
118
+ z.strictObject({ state: z.string(), forced: z.array(z.string()) }),
119
+ z.strictObject({ error: z.string() }),
120
+ ])
121
+ .nullable(),
122
+ /** A controller user is stored on the agent's PC, so requests may leave theirs out. */
123
+ credentialsStored: z.boolean(),
98
124
  });
99
125
  export type AgentStatus = z.infer<typeof statusSchema>;
100
126
 
@@ -102,32 +128,45 @@ export type AgentStatus = z.infer<typeof statusSchema>;
102
128
  export const logoutSchema = z.strictObject({ failure: z.string().optional() });
103
129
 
104
130
  /** Who ran a command, as the client reports it in these headers. */
105
- export const clientHeaders = { user: "x-tsplc-user", host: "x-tsplc-host" } as const;
131
+ export const clientHeaders = {
132
+ user: "x-tsplc-user",
133
+ host: "x-tsplc-host",
134
+ } as const;
135
+
136
+ /** Who sent a request, as the client reports it. */
137
+ export const clientIdentity = (request: Request) => {
138
+ const header = (name: string) =>
139
+ request.headers.get(name)?.slice(0, 200) || undefined;
140
+ return { user: header(clientHeaders.user), host: header(clientHeaders.host) };
141
+ };
142
+ export type ClientIdentity = ReturnType<typeof clientIdentity>;
106
143
 
107
144
  /** A line of the agent's `deployments.jsonl`. */
108
145
  export const deploymentSchema = z.strictObject({
109
- at: z.iso.datetime(),
110
- release: z.string(),
111
- /** The debug manifest's build id, when the release has one. */
112
- build: z.string().optional(),
113
- operation: z.enum(["download", "online-change"]),
114
- user: z.string().optional(),
115
- host: z.string().optional(),
146
+ at: z.iso.datetime(),
147
+ release: z.string(),
148
+ /** The debug manifest's build id, when the release has one. */
149
+ build: z.string().optional(),
150
+ operation: deployOperationSchema,
151
+ /** Whether the request sent the controller user or the agent used its stored one; lines from before 0.2.18 lack it. */
152
+ credentials: z.enum(["provided", "stored"]).optional(),
153
+ user: z.string().optional(),
154
+ host: z.string().optional(),
116
155
  });
117
156
  export type Deployment = z.infer<typeof deploymentSchema>;
118
157
 
119
158
  /** A line of the agent's `audit.jsonl`: a login command that changed the controller. */
120
159
  export const auditSchema = z.strictObject({
121
- at: z.iso.datetime(),
122
- /** As typed after `tsplc`, such as `force` or `reset cold`. */
123
- command: z.string(),
124
- /** Expressions written or forced, with their values; unforced expressions map to "". */
125
- values: z.record(z.string(), z.string()),
126
- /** The values read just before the command, when the read succeeded. */
127
- previous: z.record(z.string(), z.string()).optional(),
128
- user: z.string().optional(),
129
- host: z.string().optional(),
130
- release: z.string().optional(),
131
- error: z.string().optional(),
160
+ at: z.iso.datetime(),
161
+ /** As typed after `tsplc`, such as `force` or `reset cold`. */
162
+ command: z.string(),
163
+ /** Expressions written or forced, with their values; unforced expressions map to "". */
164
+ values: z.record(z.string(), z.string()),
165
+ /** The values read just before the command, when the read succeeded. */
166
+ previous: z.record(z.string(), z.string()).optional(),
167
+ user: z.string().optional(),
168
+ host: z.string().optional(),
169
+ release: z.string().optional(),
170
+ error: z.string().optional(),
132
171
  });
133
172
  export type Audit = z.infer<typeof auditSchema>;