@inquir/compute 0.4.0 → 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,255 +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`); see
15
- > `packages/cli/README.md`, "Publishing to npm".
16
-
17
- ## What It Includes
18
-
19
- - `defineFunction()` and `definePipeline()` for code-first assets.
20
- - `loadConfig()` for `inquir.config.json`.
21
- - `discoverAssets()` for workspace asset scanning.
22
- - `generateCodegenArtifacts()` / `generateAndWriteCodegenArtifacts()` for typed client + `registry.json`.
23
- - `runLocally()` for local function execution/debug harness.
24
- - HTTP transport helpers (`createClient`, `invokeRemote`, deploy/list helpers).
25
- - 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`.
26
-
27
- ## Pending synchronous invocations
28
-
29
- When the server admits a finite cold invocation, `invokeRemote()` submits once
30
- and follows only the authenticated invocation's `/resume` endpoint. Hot
31
- invocations keep their existing path. Save each handle from `onPending` if the
32
- caller must survive a restart:
33
-
34
- ```ts
35
- import { invokeRemote, resumeRemoteInvocation, cancelRemoteInvocation,
36
- RemoteInvocationObservationEndedError } from '@inquir/compute';
37
-
38
- try {
39
- const result = await invokeRemote(client, 'my-function', event, {
40
- timeoutMs: 120_000, signal, onPending: saveHandle,
41
- });
42
- } catch (error) {
43
- if (error instanceof RemoteInvocationObservationEndedError) {
44
- saveHandle(error.pending); // PENDING/RECOVERY_HELD is not FAILED.
45
- // Later: await resumeRemoteInvocation(client, error.pending);
46
- // Explicit intent: await cancelRemoteInvocation(client, error.pending);
47
- } else throw error;
48
- }
49
- ```
50
-
51
- Abort/timeout stops observation, not execution. A cancellation receipt records
52
- intent, not a terminal outcome. If the initial POST reply is lost before a handle
53
- arrives, this adapter cannot recover an unknown server ID and never repeats that
54
- POST. Server admission remains independently gated; this client does not enable
55
- gateway, pipeline, durable or streaming finite execution.
56
-
57
- ## Durable source commands
58
-
59
- Source execution uses an explicit operation instead of synchronous writable
60
- `/exec`. Save a lowercase UUID v4 before preparing, and atomically retain every
61
- record supplied by the callback in private storage. Records contain command/env
62
- secrets; they contain a credential hash rather than the credential itself.
63
-
64
- ```ts
65
- import { createClient, prepareSourceCommand, restoreSourceCommand } from '@inquir/compute';
66
-
67
- const client = createClient({ baseUrl: apiUrl, apiKey, workspaceId });
68
- const operation = await prepareSourceCommand(client, {
69
- function: 'my-function', requestId: savedUuid,
70
- input: { command: 'npm install', timeoutMs: 60_000 },
71
- retain: savePrivateRecordAtomically,
72
- });
73
- await operation.submit(); // no automatic POST retry
74
- const state = await operation.status(); // GET only
75
- const publication = await operation.reconcile(); // explicit source publication
76
- // await operation.cancel(); // explicit cancellation intent
77
- const restored = await restoreSourceCommand(client, savedRecord, {
78
- retain: savePrivateRecordAtomically,
79
- }); // no HTTP or submission
80
- ```
81
-
82
- The retained API, credential hash, original workspace selector and resolved
83
- workspace/function IDs must match on restore. Later actions stay pinned to those
84
- IDs even if the client changes. A lost response keeps the same operation UUID;
85
- inspect status or explicitly retry the same action. Poll timeout/abort stops
86
- observation and does not cancel or publish. `EXITED` and `CANCEL_REQUESTED` do not
87
- prove physical removal or capacity release. A GET with `publication: null` does
88
- not prove that an earlier explicit publication never happened.
89
-
90
- Acceptance identity is retained before an action returns and after each poll
91
- response. If storage fails, further HTTP is blocked until the pending record is
92
- saved; `operation.persist()` retries storage without HTTP. Keep the updated
93
- record returned by `record()` for reloads. The server must enable the source
94
- command API after its activation gates; a 503 never falls back to writable exec.
95
-
96
- `result.logFailure` and `sourcePublicationState(outcome) === 'CAPTURE_FAILED'`
97
- mark unavailable log capture, preserving the real termination and exit code.
98
- Blank Base64 fields then mean unavailable capture rather than successful empty
99
- logs; workspace output is absent and cannot be published.
100
-
101
- ## Concepts
102
-
103
- - **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.
104
- - **Pipeline**: a declarative DAG of functions created with `definePipeline()`. Included in the codegen registry; orchestration is handled server-side.
105
- - **Client**: the generated `client.ts` (from `generateAndWriteCodegenArtifacts()`). Provides a type-safe `createClient()` factory that wraps `invokeRemote()` with your asset's I/O types.
106
- - **Source of truth**: local files on disk. `registry.json` is derived — rebuild it with `generateAndWriteCodegenArtifacts()` whenever sources change.
107
- - **Local ↔ remote link**: remote functions store `linkedLocalName` (local asset name) and `sourceHash`. Compare hashes to detect drift.
108
-
109
- ## Quick Example
110
-
111
- ```ts
112
- import { defineFunction } from '@inquir/compute';
113
- import { z } from 'zod';
114
-
115
- export const hello = defineFunction(
116
- {
117
- name: 'hello',
118
- input: z.object({ name: z.string().optional() }),
119
- output: z.object({ message: z.string() }),
120
- },
121
- async (input) => ({ message: `Hello, ${input.name ?? 'world'}` })
122
- );
123
- ```
124
-
125
- ## Minimal Workspace Config
126
-
127
- Create `inquir.config.json`:
128
-
129
- ```json
130
- {
131
- "functionsDir": "inquir/functions",
132
- "pipelinesDir": "inquir/pipelines",
133
- "generatedDir": ".inquir/generated"
134
- }
135
- ```
136
-
137
- ## Discovery + Codegen
138
-
139
- ```ts
140
- import { discoverAssets, generateAndWriteCodegenArtifacts, loadConfig } from '@inquir/compute';
141
-
142
- const config = loadConfig(process.cwd());
143
- const registry = await discoverAssets(config);
144
- await generateAndWriteCodegenArtifacts(config.absoluteGeneratedDir, registry);
145
- ```
146
-
147
- This generates:
148
-
149
- - `.inquir/generated/client.ts`
150
- - `.inquir/generated/registry.json`
151
-
152
- `registry.json` includes stable metadata such as `name`, `kind`, `sourceHash`, and `assetRoot`.
153
-
154
- ## Local Run
155
-
156
- ```ts
157
- import { runLocally } from '@inquir/compute';
158
-
159
- const result = await runLocally(
160
- {
161
- kind: 'function',
162
- name: 'hello',
163
- filePath: '/abs/path/inquir/functions/hello/index.ts',
164
- exportName: 'hello',
165
- },
166
- { name: 'World' }
167
- );
168
- ```
169
-
170
- ## Remote Invoke (Transport)
171
-
172
- ```ts
173
- import { createClient, invokeRemote } from '@inquir/compute';
174
-
175
- const client = createClient({ baseUrl: 'http://localhost:3000', apiKey: process.env.INQUIR_API_KEY });
176
- const response = await invokeRemote(client, 'hello', { name: 'World' });
177
- ```
178
-
179
- ## Readonly published-release commands (scoped rollout)
180
-
181
- `prepareReleaseCommand` retains the caller's original UUID, workspace and command
182
- before the first HTTP submission. It uses the dedicated readonly release API;
183
- it does not invoke the writable source-command API or a function handler.
184
-
185
- ```ts
186
- import { randomUUID } from 'node:crypto';
187
- import { prepareReleaseCommand, restoreReleaseCommand } from '@inquir/compute';
188
-
189
- const operation = await prepareReleaseCommand(client, {
190
- functionId,
191
- requestId: randomUUID(),
192
- input: { command: 'cat package.json', timeoutMs: 60_000 },
193
- retain: async record => saveCommandRecord(record), // Durable caller storage.
194
- });
195
- const first = await operation.submit(); // Submit once. Keep the retained record on a lost reply.
196
- const outcome = first.state === 'PENDING' || first.state === 'RECOVERY_HELD'
197
- ? await restoreReleaseCommand(client, operation.record()).observe()
198
- : first;
199
- ```
200
-
201
- Observation resumes the same ID and never repeats the initial POST. An expired
202
- or aborted observer keeps that handle; `operation.cancel()` separately requests
203
- durable cancellation. Cancellation acknowledgement is an intent, while `REMOVED`
204
- is a validated terminal result after physical task/container cleanup. Scope or
205
- artifact uncertainty remains held rather than becoming a fabricated failure.
206
- `CANCELLED_WITHOUT_CONTAINER` separately proves an admitted reservation was
207
- cancelled and physically retired before CREATE; its `result` is `null` because
208
- no shell ran. `CANCELLED_BEFORE_ADMISSION` has no reservation to retire.
209
-
210
- This path is disabled by default. Each exact runtime image, readonly process,
211
- source/input mount, resource and network profile must receive native
212
- qualification before its scoped operator approval and rollout switches enable
213
- admission. The initial source tests do not constitute that qualification.
214
-
215
- ## Application observability
216
-
217
- 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:
218
-
219
- ```ts
220
- import {
221
- createClient, getAppMetrics, getAppHttpMetrics, getAppLogHistory,
222
- createAppAlertRule, updateAppAlertRule, listAppAlertIncidents,
223
- } from '@inquir/compute';
224
-
225
- const client = createClient({
226
- baseUrl: 'https://inquir.org/api',
227
- apiKey: process.env.INQUIR_TOKEN,
228
- workspaceId: process.env.INQUIR_WORKSPACE,
229
- });
230
- const to = new Date().toISOString();
231
- const from = new Date(Date.now() - 60 * 60 * 1000).toISOString();
232
- const resources = await getAppMetrics(client, appId, { from, to });
233
- const http = await getAppHttpMetrics(client, appId, { from, to });
234
- const logs = await getAppLogHistory(client, appId, {
235
- from, to, releaseId, allocationId, allocationFence: 4, level: 'error', limit: 100,
236
- });
237
- if (logs.nextCursor) {
238
- const older = await getAppLogHistory(client, appId, {
239
- from: logs.from, to: logs.to, releaseId, allocationId, allocationFence: 4,
240
- level: 'error', limit: 100, cursor: logs.nextCursor,
241
- });
242
- }
243
-
244
- const { rule } = await createAppAlertRule(client, appId, {
245
- name: 'High RAM', enabled: true, metric: 'memory_percent',
246
- threshold: 85, forSeconds: 120, recoveryThreshold: 65,
247
- recoveryForSeconds: 60, noDataSeconds: 180, noData: 'alert', channels: [],
248
- });
249
- await updateAppAlertRule(client, appId, rule.id, { threshold: 90 });
250
- const { incidents } = await listAppAlertIncidents(client, appId, { limit: 25 });
251
- ```
252
-
253
- `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.
254
-
255
- 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.
@@ -42,6 +42,54 @@ export declare function getAppResourceRecommendation(client: TransportClient, ap
42
42
  * Read-only.
43
43
  */
44
44
  export declare function describeApp(client: TransportClient, appId: string): Promise<AppDescribeResponse>;
45
+ /** One replica of an application, the pod analog (docs/design/REPLICA_SELECTION.md). */
46
+ export interface AppInstance {
47
+ /** `<app>-<replicaIndex>-<allocationId[0..8]>`: stable for one attempt, new for a replacement. */
48
+ name: string;
49
+ /** Null only for a legacy (pre-allocation) single container. */
50
+ allocationId: string | null;
51
+ releaseId: string;
52
+ production: boolean;
53
+ replicaIndex: number;
54
+ incarnation: number;
55
+ /** Earlier attempts of this slot in this release. */
56
+ restarts: number;
57
+ state: string;
58
+ /** Serving production traffic right now. */
59
+ ready: boolean;
60
+ console: 'available' | 'remote_unsupported' | 'unavailable';
61
+ runner: {
62
+ id: string;
63
+ provider: string;
64
+ region: string | null;
65
+ } | null;
66
+ createdAt: string;
67
+ startedAt: string | null;
68
+ readyAt: string | null;
69
+ failure: string | null;
70
+ usage: {
71
+ cpuUsedCores: number | null;
72
+ cpuPercent: number | null;
73
+ memoryWorkingSetBytes: number | null;
74
+ memoryPercent: number | null;
75
+ sampledAt: string;
76
+ } | null;
77
+ conditions: AppDescribeResponse['application']['conditions'];
78
+ }
79
+ export interface AppInstancesResponse {
80
+ applicationId: string;
81
+ productionReleaseId: string | null;
82
+ generatedAt: string;
83
+ instances: AppInstance[];
84
+ }
85
+ /** The application's replicas: name, state, runner, readiness, restarts, CPU/memory now. */
86
+ export declare function listAppInstances(client: TransportClient, appId: string): Promise<AppInstancesResponse>;
87
+ /**
88
+ * Resolve a replica selector the way the server does: exact allocation id,
89
+ * instance name (`...-<index>-<id8>`), bare replica index (the ready one
90
+ * first), or a unique allocation-id prefix of at least 8 characters.
91
+ */
92
+ export declare function matchAppInstance(selector: string, instances: readonly AppInstance[]): AppInstance | null;
45
93
  /** HTTP gateway observations; private TCP traffic is not HTTP request telemetry. */
46
94
  export declare function getAppHttpMetrics(client: TransportClient, appId: string, range?: AppObservationRange): Promise<AppHttpMetricsResponse>;
47
95
  /** One descending timestamp/id page of persisted runtime logs (7-day retention). */
@@ -1 +1 @@
1
- {"version":3,"file":"app-observability.d.ts","sourceRoot":"","sources":["../src/app-observability.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,KAA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