@inquir/compute 0.4.1 → 0.4.2

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/README.md CHANGED
@@ -1,256 +1,257 @@
1
- # @inquir/compute
2
-
3
- Workspace-first SDK for defining, discovering, generating, and running Inquir Compute assets.
4
-
5
- ## Install
6
-
7
- Requires Node.js 22 or newer. Version 0.3 groups only long-lived container applications in projects; functions and pipelines remain separate assets.
8
-
9
- ```bash
10
- npm install @inquir/compute zod@^3.23.8
11
- ```
12
-
13
- > Release order: publish this SDK before the CLI that depends on it. CLI 0.4.0
14
- > needs SDK 0.4.0 (`isPromoteAccepted`, `getApplicationRollout`); the next CLI
15
- > needs SDK 0.4.1 (`listAppInstances`, `matchAppInstance`); see
16
- > `packages/cli/README.md`, "Publishing to npm".
17
-
18
- ## What It Includes
19
-
20
- - `defineFunction()` and `definePipeline()` for code-first assets.
21
- - `loadConfig()` for `inquir.config.json`.
22
- - `discoverAssets()` for workspace asset scanning.
23
- - `generateCodegenArtifacts()` / `generateAndWriteCodegenArtifacts()` for typed client + `registry.json`.
24
- - `runLocally()` for local function execution/debug harness.
25
- - HTTP transport helpers (`createClient`, `invokeRemote`, deploy/list helpers).
26
- - Application project helpers (`listProjects`, `createProject`, `getProject`, `addProjectResource`) group long-lived containers: web services, APIs, databases, and workers. Project members use `kind: 'application'`; serverless functions are managed separately. `createApplication` accepts `projectId` (ID or slug); omitting it creates a project named after the application. Archiving a project also archives all its applications, including an application shared with another project. Removing a membership leaves it running. Project lifecycle actions require `projects:write` and `apps:promote`.
27
-
28
- ## Pending synchronous invocations
29
-
30
- When the server admits a finite cold invocation, `invokeRemote()` submits once
31
- and follows only the authenticated invocation's `/resume` endpoint. Hot
32
- invocations keep their existing path. Save each handle from `onPending` if the
33
- caller must survive a restart:
34
-
35
- ```ts
36
- import { invokeRemote, resumeRemoteInvocation, cancelRemoteInvocation,
37
- RemoteInvocationObservationEndedError } from '@inquir/compute';
38
-
39
- try {
40
- const result = await invokeRemote(client, 'my-function', event, {
41
- timeoutMs: 120_000, signal, onPending: saveHandle,
42
- });
43
- } catch (error) {
44
- if (error instanceof RemoteInvocationObservationEndedError) {
45
- saveHandle(error.pending); // PENDING/RECOVERY_HELD is not FAILED.
46
- // Later: await resumeRemoteInvocation(client, error.pending);
47
- // Explicit intent: await cancelRemoteInvocation(client, error.pending);
48
- } else throw error;
49
- }
50
- ```
51
-
52
- Abort/timeout stops observation, not execution. A cancellation receipt records
53
- intent, not a terminal outcome. If the initial POST reply is lost before a handle
54
- arrives, this adapter cannot recover an unknown server ID and never repeats that
55
- POST. Server admission remains independently gated; this client does not enable
56
- gateway, pipeline, durable or streaming finite execution.
57
-
58
- ## Durable source commands
59
-
60
- Source execution uses an explicit operation instead of synchronous writable
61
- `/exec`. Save a lowercase UUID v4 before preparing, and atomically retain every
62
- record supplied by the callback in private storage. Records contain command/env
63
- secrets; they contain a credential hash rather than the credential itself.
64
-
65
- ```ts
66
- import { createClient, prepareSourceCommand, restoreSourceCommand } from '@inquir/compute';
67
-
68
- const client = createClient({ baseUrl: apiUrl, apiKey, workspaceId });
69
- const operation = await prepareSourceCommand(client, {
70
- function: 'my-function', requestId: savedUuid,
71
- input: { command: 'npm install', timeoutMs: 60_000 },
72
- retain: savePrivateRecordAtomically,
73
- });
74
- await operation.submit(); // no automatic POST retry
75
- const state = await operation.status(); // GET only
76
- const publication = await operation.reconcile(); // explicit source publication
77
- // await operation.cancel(); // explicit cancellation intent
78
- const restored = await restoreSourceCommand(client, savedRecord, {
79
- retain: savePrivateRecordAtomically,
80
- }); // no HTTP or submission
81
- ```
82
-
83
- The retained API, credential hash, original workspace selector and resolved
84
- workspace/function IDs must match on restore. Later actions stay pinned to those
85
- IDs even if the client changes. A lost response keeps the same operation UUID;
86
- inspect status or explicitly retry the same action. Poll timeout/abort stops
87
- observation and does not cancel or publish. `EXITED` and `CANCEL_REQUESTED` do not
88
- prove physical removal or capacity release. A GET with `publication: null` does
89
- not prove that an earlier explicit publication never happened.
90
-
91
- Acceptance identity is retained before an action returns and after each poll
92
- response. If storage fails, further HTTP is blocked until the pending record is
93
- saved; `operation.persist()` retries storage without HTTP. Keep the updated
94
- record returned by `record()` for reloads. The server must enable the source
95
- command API after its activation gates; a 503 never falls back to writable exec.
96
-
97
- `result.logFailure` and `sourcePublicationState(outcome) === 'CAPTURE_FAILED'`
98
- mark unavailable log capture, preserving the real termination and exit code.
99
- Blank Base64 fields then mean unavailable capture rather than successful empty
100
- logs; workspace output is absent and cannot be published.
101
-
102
- ## Concepts
103
-
104
- - **Function**: a single compute unit with typed input/output (Zod schemas). Created with `defineFunction()`. Discovered by file pattern, run locally via `runLocally()`, deployed and invoked remotely via the transport helpers.
105
- - **Pipeline**: a declarative DAG of functions created with `definePipeline()`. Included in the codegen registry; orchestration is handled server-side.
106
- - **Client**: the generated `client.ts` (from `generateAndWriteCodegenArtifacts()`). Provides a type-safe `createClient()` factory that wraps `invokeRemote()` with your asset's I/O types.
107
- - **Source of truth**: local files on disk. `registry.json` is derived — rebuild it with `generateAndWriteCodegenArtifacts()` whenever sources change.
108
- - **Local ↔ remote link**: remote functions store `linkedLocalName` (local asset name) and `sourceHash`. Compare hashes to detect drift.
109
-
110
- ## Quick Example
111
-
112
- ```ts
113
- import { defineFunction } from '@inquir/compute';
114
- import { z } from 'zod';
115
-
116
- export const hello = defineFunction(
117
- {
118
- name: 'hello',
119
- input: z.object({ name: z.string().optional() }),
120
- output: z.object({ message: z.string() }),
121
- },
122
- async (input) => ({ message: `Hello, ${input.name ?? 'world'}` })
123
- );
124
- ```
125
-
126
- ## Minimal Workspace Config
127
-
128
- Create `inquir.config.json`:
129
-
130
- ```json
131
- {
132
- "functionsDir": "inquir/functions",
133
- "pipelinesDir": "inquir/pipelines",
134
- "generatedDir": ".inquir/generated"
135
- }
136
- ```
137
-
138
- ## Discovery + Codegen
139
-
140
- ```ts
141
- import { discoverAssets, generateAndWriteCodegenArtifacts, loadConfig } from '@inquir/compute';
142
-
143
- const config = loadConfig(process.cwd());
144
- const registry = await discoverAssets(config);
145
- await generateAndWriteCodegenArtifacts(config.absoluteGeneratedDir, registry);
146
- ```
147
-
148
- This generates:
149
-
150
- - `.inquir/generated/client.ts`
151
- - `.inquir/generated/registry.json`
152
-
153
- `registry.json` includes stable metadata such as `name`, `kind`, `sourceHash`, and `assetRoot`.
154
-
155
- ## Local Run
156
-
157
- ```ts
158
- import { runLocally } from '@inquir/compute';
159
-
160
- const result = await runLocally(
161
- {
162
- kind: 'function',
163
- name: 'hello',
164
- filePath: '/abs/path/inquir/functions/hello/index.ts',
165
- exportName: 'hello',
166
- },
167
- { name: 'World' }
168
- );
169
- ```
170
-
171
- ## Remote Invoke (Transport)
172
-
173
- ```ts
174
- import { createClient, invokeRemote } from '@inquir/compute';
175
-
176
- const client = createClient({ baseUrl: 'http://localhost:3000', apiKey: process.env.INQUIR_API_KEY });
177
- const response = await invokeRemote(client, 'hello', { name: 'World' });
178
- ```
179
-
180
- ## Readonly published-release commands (scoped rollout)
181
-
182
- `prepareReleaseCommand` retains the caller's original UUID, workspace and command
183
- before the first HTTP submission. It uses the dedicated readonly release API;
184
- it does not invoke the writable source-command API or a function handler.
185
-
186
- ```ts
187
- import { randomUUID } from 'node:crypto';
188
- import { prepareReleaseCommand, restoreReleaseCommand } from '@inquir/compute';
189
-
190
- const operation = await prepareReleaseCommand(client, {
191
- functionId,
192
- requestId: randomUUID(),
193
- input: { command: 'cat package.json', timeoutMs: 60_000 },
194
- retain: async record => saveCommandRecord(record), // Durable caller storage.
195
- });
196
- const first = await operation.submit(); // Submit once. Keep the retained record on a lost reply.
197
- const outcome = first.state === 'PENDING' || first.state === 'RECOVERY_HELD'
198
- ? await restoreReleaseCommand(client, operation.record()).observe()
199
- : first;
200
- ```
201
-
202
- Observation resumes the same ID and never repeats the initial POST. An expired
203
- or aborted observer keeps that handle; `operation.cancel()` separately requests
204
- durable cancellation. Cancellation acknowledgement is an intent, while `REMOVED`
205
- is a validated terminal result after physical task/container cleanup. Scope or
206
- artifact uncertainty remains held rather than becoming a fabricated failure.
207
- `CANCELLED_WITHOUT_CONTAINER` separately proves an admitted reservation was
208
- cancelled and physically retired before CREATE; its `result` is `null` because
209
- no shell ran. `CANCELLED_BEFORE_ADMISSION` has no reservation to retire.
210
-
211
- This path is disabled by default. Each exact runtime image, readonly process,
212
- source/input mount, resource and network profile must receive native
213
- qualification before its scoped operator approval and rollout switches enable
214
- admission. The initial source tests do not constitute that qualification.
215
-
216
- ## Application observability
217
-
218
- The SDK exposes resource and HTTP history, persisted runtime/HTTP logs and configurable app alerts. Every helper uses the client's credentials and workspace selector:
219
-
220
- ```ts
221
- import {
222
- createClient, getAppMetrics, getAppHttpMetrics, getAppLogHistory,
223
- createAppAlertRule, updateAppAlertRule, listAppAlertIncidents,
224
- } from '@inquir/compute';
225
-
226
- const client = createClient({
227
- baseUrl: 'https://inquir.org/api',
228
- apiKey: process.env.INQUIR_TOKEN,
229
- workspaceId: process.env.INQUIR_WORKSPACE,
230
- });
231
- const to = new Date().toISOString();
232
- const from = new Date(Date.now() - 60 * 60 * 1000).toISOString();
233
- const resources = await getAppMetrics(client, appId, { from, to });
234
- const http = await getAppHttpMetrics(client, appId, { from, to });
235
- const logs = await getAppLogHistory(client, appId, {
236
- from, to, releaseId, allocationId, allocationFence: 4, level: 'error', limit: 100,
237
- });
238
- if (logs.nextCursor) {
239
- const older = await getAppLogHistory(client, appId, {
240
- from: logs.from, to: logs.to, releaseId, allocationId, allocationFence: 4,
241
- level: 'error', limit: 100, cursor: logs.nextCursor,
242
- });
243
- }
244
-
245
- const { rule } = await createAppAlertRule(client, appId, {
246
- name: 'High RAM', enabled: true, metric: 'memory_percent',
247
- threshold: 85, forSeconds: 120, recoveryThreshold: 65,
248
- recoveryForSeconds: 60, noDataSeconds: 180, noData: 'alert', channels: [],
249
- });
250
- await updateAppAlertRule(client, appId, rule.id, { threshold: 90 });
251
- const { incidents } = await listAppAlertIncidents(client, appId, { limit: 25 });
252
- ```
253
-
254
- `getAppHttpLogHistory`, `listAppAlertRules` and `deleteAppAlertRule` complete the API. Deletion disables the rule and resolves its active incidents; retained history is still available. Omit `channels` in a patch to preserve existing destinations, or pass an empty array to remove them. `webhook`/`slack` channel URLs are write-only; response types expose only channel id, type and configured status. Never log alert request inputs containing a secret URL.
255
-
256
- Resource and HTTP retention is 30 days; runtime logs are retained for 7 days. Runtime history is attributed to the exact release, allocation/fence, runner/epoch and container, including replaced containers. Paging is newest-first and requires an unchanged date window and filters. Resource history retains unavailable values as `null`; use `status`, `latestSampleAt` and `truncated` to detect stale or incomplete results. Network and block I/O rates are measured separately; block I/O is not volume space usage. CPU/RAM alert percentages are relative to enforced limits, and the continuous maximum across current production replicas determines threshold firing.
1
+ # @inquir/compute
2
+
3
+ Workspace-first SDK for defining, discovering, generating, and running Inquir Compute assets.
4
+
5
+ ## Install
6
+
7
+ Requires Node.js 22 or newer. Version 0.3 groups only long-lived container applications in projects; functions and pipelines remain separate assets.
8
+
9
+ ```bash
10
+ npm install @inquir/compute zod@^3.23.8
11
+ ```
12
+
13
+ > Release order: publish this SDK before the CLI that depends on it. CLI 0.4.0
14
+ > needs SDK 0.4.0 (`isPromoteAccepted`, `getApplicationRollout`); CLI 0.4.1
15
+ > needs SDK 0.4.2 (`listAppInstances`, `matchAppInstance`, `createSourceArchive`,
16
+ > `manifestBuildContext`, `getProductionReplacement`);
17
+ > see `packages/cli/README.md`, "Publishing to npm".
18
+
19
+ ## What It Includes
20
+
21
+ - `defineFunction()` and `definePipeline()` for code-first assets.
22
+ - `loadConfig()` for `inquir.config.json`.
23
+ - `discoverAssets()` for workspace asset scanning.
24
+ - `generateCodegenArtifacts()` / `generateAndWriteCodegenArtifacts()` for typed client + `registry.json`.
25
+ - `runLocally()` for local function execution/debug harness.
26
+ - HTTP transport helpers (`createClient`, `invokeRemote`, deploy/list helpers).
27
+ - Application project helpers (`listProjects`, `createProject`, `getProject`, `addProjectResource`) group long-lived containers: web services, APIs, databases, and workers. Project members use `kind: 'application'`; serverless functions are managed separately. `createApplication` accepts `projectId` (ID or slug); omitting it creates a project named after the application. Archiving a project also archives all its applications, including an application shared with another project. Removing a membership leaves it running. Project lifecycle actions require `projects:write` and `apps:promote`.
28
+
29
+ ## Pending synchronous invocations
30
+
31
+ When the server admits a finite cold invocation, `invokeRemote()` submits once
32
+ and follows only the authenticated invocation's `/resume` endpoint. Hot
33
+ invocations keep their existing path. Save each handle from `onPending` if the
34
+ caller must survive a restart:
35
+
36
+ ```ts
37
+ import { invokeRemote, resumeRemoteInvocation, cancelRemoteInvocation,
38
+ RemoteInvocationObservationEndedError } from '@inquir/compute';
39
+
40
+ try {
41
+ const result = await invokeRemote(client, 'my-function', event, {
42
+ timeoutMs: 120_000, signal, onPending: saveHandle,
43
+ });
44
+ } catch (error) {
45
+ if (error instanceof RemoteInvocationObservationEndedError) {
46
+ saveHandle(error.pending); // PENDING/RECOVERY_HELD is not FAILED.
47
+ // Later: await resumeRemoteInvocation(client, error.pending);
48
+ // Explicit intent: await cancelRemoteInvocation(client, error.pending);
49
+ } else throw error;
50
+ }
51
+ ```
52
+
53
+ Abort/timeout stops observation, not execution. A cancellation receipt records
54
+ intent, not a terminal outcome. If the initial POST reply is lost before a handle
55
+ arrives, this adapter cannot recover an unknown server ID and never repeats that
56
+ POST. Server admission remains independently gated; this client does not enable
57
+ gateway, pipeline, durable or streaming finite execution.
58
+
59
+ ## Durable source commands
60
+
61
+ Source execution uses an explicit operation instead of synchronous writable
62
+ `/exec`. Save a lowercase UUID v4 before preparing, and atomically retain every
63
+ record supplied by the callback in private storage. Records contain command/env
64
+ secrets; they contain a credential hash rather than the credential itself.
65
+
66
+ ```ts
67
+ import { createClient, prepareSourceCommand, restoreSourceCommand } from '@inquir/compute';
68
+
69
+ const client = createClient({ baseUrl: apiUrl, apiKey, workspaceId });
70
+ const operation = await prepareSourceCommand(client, {
71
+ function: 'my-function', requestId: savedUuid,
72
+ input: { command: 'npm install', timeoutMs: 60_000 },
73
+ retain: savePrivateRecordAtomically,
74
+ });
75
+ await operation.submit(); // no automatic POST retry
76
+ const state = await operation.status(); // GET only
77
+ const publication = await operation.reconcile(); // explicit source publication
78
+ // await operation.cancel(); // explicit cancellation intent
79
+ const restored = await restoreSourceCommand(client, savedRecord, {
80
+ retain: savePrivateRecordAtomically,
81
+ }); // no HTTP or submission
82
+ ```
83
+
84
+ The retained API, credential hash, original workspace selector and resolved
85
+ workspace/function IDs must match on restore. Later actions stay pinned to those
86
+ IDs even if the client changes. A lost response keeps the same operation UUID;
87
+ inspect status or explicitly retry the same action. Poll timeout/abort stops
88
+ observation and does not cancel or publish. `EXITED` and `CANCEL_REQUESTED` do not
89
+ prove physical removal or capacity release. A GET with `publication: null` does
90
+ not prove that an earlier explicit publication never happened.
91
+
92
+ Acceptance identity is retained before an action returns and after each poll
93
+ response. If storage fails, further HTTP is blocked until the pending record is
94
+ saved; `operation.persist()` retries storage without HTTP. Keep the updated
95
+ record returned by `record()` for reloads. The server must enable the source
96
+ command API after its activation gates; a 503 never falls back to writable exec.
97
+
98
+ `result.logFailure` and `sourcePublicationState(outcome) === 'CAPTURE_FAILED'`
99
+ mark unavailable log capture, preserving the real termination and exit code.
100
+ Blank Base64 fields then mean unavailable capture rather than successful empty
101
+ logs; workspace output is absent and cannot be published.
102
+
103
+ ## Concepts
104
+
105
+ - **Function**: a single compute unit with typed input/output (Zod schemas). Created with `defineFunction()`. Discovered by file pattern, run locally via `runLocally()`, deployed and invoked remotely via the transport helpers.
106
+ - **Pipeline**: a declarative DAG of functions created with `definePipeline()`. Included in the codegen registry; orchestration is handled server-side.
107
+ - **Client**: the generated `client.ts` (from `generateAndWriteCodegenArtifacts()`). Provides a type-safe `createClient()` factory that wraps `invokeRemote()` with your asset's I/O types.
108
+ - **Source of truth**: local files on disk. `registry.json` is derived — rebuild it with `generateAndWriteCodegenArtifacts()` whenever sources change.
109
+ - **Local ↔ remote link**: remote functions store `linkedLocalName` (local asset name) and `sourceHash`. Compare hashes to detect drift.
110
+
111
+ ## Quick Example
112
+
113
+ ```ts
114
+ import { defineFunction } from '@inquir/compute';
115
+ import { z } from 'zod';
116
+
117
+ export const hello = defineFunction(
118
+ {
119
+ name: 'hello',
120
+ input: z.object({ name: z.string().optional() }),
121
+ output: z.object({ message: z.string() }),
122
+ },
123
+ async (input) => ({ message: `Hello, ${input.name ?? 'world'}` })
124
+ );
125
+ ```
126
+
127
+ ## Minimal Workspace Config
128
+
129
+ Create `inquir.config.json`:
130
+
131
+ ```json
132
+ {
133
+ "functionsDir": "inquir/functions",
134
+ "pipelinesDir": "inquir/pipelines",
135
+ "generatedDir": ".inquir/generated"
136
+ }
137
+ ```
138
+
139
+ ## Discovery + Codegen
140
+
141
+ ```ts
142
+ import { discoverAssets, generateAndWriteCodegenArtifacts, loadConfig } from '@inquir/compute';
143
+
144
+ const config = loadConfig(process.cwd());
145
+ const registry = await discoverAssets(config);
146
+ await generateAndWriteCodegenArtifacts(config.absoluteGeneratedDir, registry);
147
+ ```
148
+
149
+ This generates:
150
+
151
+ - `.inquir/generated/client.ts`
152
+ - `.inquir/generated/registry.json`
153
+
154
+ `registry.json` includes stable metadata such as `name`, `kind`, `sourceHash`, and `assetRoot`.
155
+
156
+ ## Local Run
157
+
158
+ ```ts
159
+ import { runLocally } from '@inquir/compute';
160
+
161
+ const result = await runLocally(
162
+ {
163
+ kind: 'function',
164
+ name: 'hello',
165
+ filePath: '/abs/path/inquir/functions/hello/index.ts',
166
+ exportName: 'hello',
167
+ },
168
+ { name: 'World' }
169
+ );
170
+ ```
171
+
172
+ ## Remote Invoke (Transport)
173
+
174
+ ```ts
175
+ import { createClient, invokeRemote } from '@inquir/compute';
176
+
177
+ const client = createClient({ baseUrl: 'http://localhost:3000', apiKey: process.env.INQUIR_API_KEY });
178
+ const response = await invokeRemote(client, 'hello', { name: 'World' });
179
+ ```
180
+
181
+ ## Readonly published-release commands (scoped rollout)
182
+
183
+ `prepareReleaseCommand` retains the caller's original UUID, workspace and command
184
+ before the first HTTP submission. It uses the dedicated readonly release API;
185
+ it does not invoke the writable source-command API or a function handler.
186
+
187
+ ```ts
188
+ import { randomUUID } from 'node:crypto';
189
+ import { prepareReleaseCommand, restoreReleaseCommand } from '@inquir/compute';
190
+
191
+ const operation = await prepareReleaseCommand(client, {
192
+ functionId,
193
+ requestId: randomUUID(),
194
+ input: { command: 'cat package.json', timeoutMs: 60_000 },
195
+ retain: async record => saveCommandRecord(record), // Durable caller storage.
196
+ });
197
+ const first = await operation.submit(); // Submit once. Keep the retained record on a lost reply.
198
+ const outcome = first.state === 'PENDING' || first.state === 'RECOVERY_HELD'
199
+ ? await restoreReleaseCommand(client, operation.record()).observe()
200
+ : first;
201
+ ```
202
+
203
+ Observation resumes the same ID and never repeats the initial POST. An expired
204
+ or aborted observer keeps that handle; `operation.cancel()` separately requests
205
+ durable cancellation. Cancellation acknowledgement is an intent, while `REMOVED`
206
+ is a validated terminal result after physical task/container cleanup. Scope or
207
+ artifact uncertainty remains held rather than becoming a fabricated failure.
208
+ `CANCELLED_WITHOUT_CONTAINER` separately proves an admitted reservation was
209
+ cancelled and physically retired before CREATE; its `result` is `null` because
210
+ no shell ran. `CANCELLED_BEFORE_ADMISSION` has no reservation to retire.
211
+
212
+ This path is disabled by default. Each exact runtime image, readonly process,
213
+ source/input mount, resource and network profile must receive native
214
+ qualification before its scoped operator approval and rollout switches enable
215
+ admission. The initial source tests do not constitute that qualification.
216
+
217
+ ## Application observability
218
+
219
+ The SDK exposes resource and HTTP history, persisted runtime/HTTP logs and configurable app alerts. Every helper uses the client's credentials and workspace selector:
220
+
221
+ ```ts
222
+ import {
223
+ createClient, getAppMetrics, getAppHttpMetrics, getAppLogHistory,
224
+ createAppAlertRule, updateAppAlertRule, listAppAlertIncidents,
225
+ } from '@inquir/compute';
226
+
227
+ const client = createClient({
228
+ baseUrl: 'https://inquir.org/api',
229
+ apiKey: process.env.INQUIR_TOKEN,
230
+ workspaceId: process.env.INQUIR_WORKSPACE,
231
+ });
232
+ const to = new Date().toISOString();
233
+ const from = new Date(Date.now() - 60 * 60 * 1000).toISOString();
234
+ const resources = await getAppMetrics(client, appId, { from, to });
235
+ const http = await getAppHttpMetrics(client, appId, { from, to });
236
+ const logs = await getAppLogHistory(client, appId, {
237
+ from, to, releaseId, allocationId, allocationFence: 4, level: 'error', limit: 100,
238
+ });
239
+ if (logs.nextCursor) {
240
+ const older = await getAppLogHistory(client, appId, {
241
+ from: logs.from, to: logs.to, releaseId, allocationId, allocationFence: 4,
242
+ level: 'error', limit: 100, cursor: logs.nextCursor,
243
+ });
244
+ }
245
+
246
+ const { rule } = await createAppAlertRule(client, appId, {
247
+ name: 'High RAM', enabled: true, metric: 'memory_percent',
248
+ threshold: 85, forSeconds: 120, recoveryThreshold: 65,
249
+ recoveryForSeconds: 60, noDataSeconds: 180, noData: 'alert', channels: [],
250
+ });
251
+ await updateAppAlertRule(client, appId, rule.id, { threshold: 90 });
252
+ const { incidents } = await listAppAlertIncidents(client, appId, { limit: 25 });
253
+ ```
254
+
255
+ `getAppHttpLogHistory`, `listAppAlertRules` and `deleteAppAlertRule` complete the API. Deletion disables the rule and resolves its active incidents; retained history is still available. Omit `channels` in a patch to preserve existing destinations, or pass an empty array to remove them. `webhook`/`slack` channel URLs are write-only; response types expose only channel id, type and configured status. Never log alert request inputs containing a secret URL.
256
+
257
+ Resource and HTTP retention is 30 days; runtime logs are retained for 7 days. Runtime history is attributed to the exact release, allocation/fence, runner/epoch and container, including replaced containers. Paging is newest-first and requires an unchanged date window and filters. Resource history retains unavailable values as `null`; use `status`, `latestSampleAt` and `truncated` to detect stale or incomplete results. Network and block I/O rates are measured separately; block I/O is not volume space usage. CPU/RAM alert percentages are relative to enforced limits, and the continuous maximum across current production replicas determines threshold firing.
package/dist/apps.d.ts CHANGED
@@ -582,6 +582,27 @@ export declare function listReleases(client: TransportClient, applicationId: str
582
582
  items: Release[];
583
583
  }>;
584
584
  export declare function getRelease(client: TransportClient, releaseId: string): Promise<Release>;
585
+ /**
586
+ * A stop-first replacement of production (`apps redeploy`, `deploy
587
+ * --promote` of an eligible service): the current replica is stopped before
588
+ * the new release starts, so the new release reads PENDING throughout.
589
+ */
590
+ export interface ProductionReplacementOperation {
591
+ id: string;
592
+ applicationId: string;
593
+ sourceReleaseId: string;
594
+ targetReleaseId: string;
595
+ /** RESERVED, STOPPING_SOURCE, STARTING_TARGET, ..., COMMITTED, ROLLED_BACK, CANCELLED. */
596
+ phase: string;
597
+ targetReplicas?: number;
598
+ createdAt: string;
599
+ phaseStartedAt: string;
600
+ lastError?: string;
601
+ }
602
+ /** The application's active production replacement, if any. */
603
+ export declare function getProductionReplacement(client: TransportClient, applicationId: string): Promise<{
604
+ operation: ProductionReplacementOperation | null;
605
+ }>;
585
606
  export interface PromoteResponse {
586
607
  previousReleaseId?: string;
587
608
  /** Absent for a service with no production hostname (pure TCP, or no suffix). */