@segmentstream/ontology 0.197.1 → 0.199.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +97 -0
- package/dist/analyze.d.ts +2 -0
- package/dist/analyze.js +17 -0
- package/dist/bin/check.js +12 -0
- package/dist/bin/migrate.js +1 -1
- package/dist/connection.d.ts +109 -6
- package/dist/connection.js +132 -17
- package/dist/diagnostics.d.ts +3 -3
- package/dist/diagnostics.js +2 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/manifest.d.ts +28 -0
- package/dist/manifest.js +6 -0
- package/dist/migrate/apply.d.ts +7 -1
- package/dist/migrate/apply.js +12 -3
- package/dist/migrate/model.d.ts +8 -0
- package/dist/migrate/plan.js +14 -1
- package/dist/owned-workflows.d.ts +10 -0
- package/dist/owned-workflows.js +16 -0
- package/dist/runtime/agents.js +2 -0
- package/dist/runtime/owner-departures.d.ts +35 -0
- package/dist/runtime/owner-departures.js +64 -0
- package/dist/runtime/pipeline.d.ts +15 -1
- package/dist/runtime/pipeline.js +67 -1
- package/dist/runtime/principals.d.ts +17 -2
- package/dist/runtime/principals.js +33 -2
- package/dist/runtime/service-binding.js +17 -3
- package/dist/runtime/workflow-starts.d.ts +108 -8
- package/dist/runtime/workflow-starts.js +276 -49
- package/dist/service/agent/attachments.js +27 -6
- package/dist/service/agent/authentication.d.ts +5 -0
- package/dist/service/agent/authentication.js +1 -1
- package/dist/service/agent/protocol.d.ts +4 -0
- package/dist/service/agent/protocol.js +4 -0
- package/dist/service/agent/server.js +7 -4
- package/dist/service/agent/task-caller.d.ts +4 -2
- package/dist/service/agent/task-caller.js +4 -2
- package/dist/service/authentication.d.ts +7 -0
- package/dist/service/authentication.js +12 -0
- package/dist/service/channel/telegram-pairing.d.ts +9 -0
- package/dist/service/channel/telegram-pairing.js +114 -0
- package/dist/service/chat/envelope.d.ts +7 -0
- package/dist/service/chat/envelope.js +15 -0
- package/dist/service/chat/providers/telegram.d.ts +2 -0
- package/dist/service/chat/providers/telegram.js +1 -1
- package/dist/service/config.d.ts +6 -0
- package/dist/service/connections.d.ts +17 -2
- package/dist/service/connections.js +21 -1
- package/dist/service/errors.js +27 -1
- package/dist/service/member-files.js +6 -0
- package/dist/service/operations.d.ts +8 -0
- package/dist/service/operations.js +11 -4
- package/dist/service/owned-connections.d.ts +80 -0
- package/dist/service/owned-connections.js +488 -0
- package/dist/service/runtime-contract.d.ts +34 -0
- package/dist/service/schemas.d.ts +2 -0
- package/dist/service/service.js +26 -2
- package/dist/service/workflow-errors.d.ts +12 -1
- package/dist/service/workflow-errors.js +15 -2
- package/dist/service/workflows.d.ts +22 -0
- package/dist/service/workflows.js +358 -48
- package/dist/start-recovery-contract.d.ts +17 -1
- package/dist/start-recovery-contract.js +11 -1
- package/dist/start-recovery.js +4 -1
- package/dist/storage/tables.d.ts +15 -0
- package/dist/storage/tables.js +21 -0
- package/dist/workflow.d.ts +20 -2
- package/package.json +1 -1
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
import { Effect, Layer } from "effect";
|
|
2
|
+
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
|
3
|
+
import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
|
|
4
|
+
import { CONNECTION_KEY } from "../connection.js";
|
|
5
|
+
import { actingConnectionOwner } from "../runtime/pipeline.js";
|
|
6
|
+
import { currentCaller } from "./caller-context.js";
|
|
7
|
+
import { CurrentPrincipal, crossSiteRequest, withPrincipal, } from "./authentication.js";
|
|
8
|
+
import { RequestId, forbidden, notFound, toServerResponse } from "./errors.js";
|
|
9
|
+
import { identityToken } from "./operations.js";
|
|
10
|
+
import { OwnedConnectionRetirement } from "../runtime/owner-departures.js";
|
|
11
|
+
import { OntologyBackend } from "./runtime-contract.js";
|
|
12
|
+
/**
|
|
13
|
+
* The routes a workspace user manages their own credentials of owned connections with
|
|
14
|
+
* (docs/private-connections-spec.md, "In the ontology SDK"), under the caller's own `me`, which no
|
|
15
|
+
* entity, toolset or metric may be named. Every route but the discard acts as the signed-in member
|
|
16
|
+
* and on that member's own credential: the owner is always the request's principal, and no route
|
|
17
|
+
* takes a user id. The discard names no owner at all.
|
|
18
|
+
*/
|
|
19
|
+
export const OWNED_CONNECTIONS_PATH = "/api/ontology/me/connections";
|
|
20
|
+
const NO_STORE = { "cache-control": "private, no-store" };
|
|
21
|
+
const BACKEND_TIMEOUT_MS = 15_000;
|
|
22
|
+
const MAXIMUM_CONFIRMATION = 128;
|
|
23
|
+
const MAXIMUM_TOKEN = 8192;
|
|
24
|
+
const MAXIMUM_ACCOUNT = 64;
|
|
25
|
+
const MAXIMUM_CURSOR = 256;
|
|
26
|
+
function isRecord(value) {
|
|
27
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
28
|
+
}
|
|
29
|
+
function invalid(requestId, detail) {
|
|
30
|
+
return { status: 400, body: { error: "invalid_request", detail, requestId } };
|
|
31
|
+
}
|
|
32
|
+
function unavailable(requestId, detail) {
|
|
33
|
+
return {
|
|
34
|
+
status: 503,
|
|
35
|
+
body: { error: "connection_unavailable", detail, requestId, retryable: true },
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** A credential state as backend-next answers it, on the ontology's snake_case wire. */
|
|
39
|
+
function stateOf(value) {
|
|
40
|
+
if (!isRecord(value) ||
|
|
41
|
+
typeof value.key !== "string" ||
|
|
42
|
+
typeof value.state !== "string" ||
|
|
43
|
+
typeof value.background !== "boolean" ||
|
|
44
|
+
(value.connectedAt !== null && typeof value.connectedAt !== "string")) {
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
key: value.key,
|
|
49
|
+
state: value.state,
|
|
50
|
+
connected_at: value.connectedAt,
|
|
51
|
+
background: value.background,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function callOf(value) {
|
|
55
|
+
if (!isRecord(value) ||
|
|
56
|
+
typeof value.calledAt !== "string" ||
|
|
57
|
+
typeof value.callKind !== "string" ||
|
|
58
|
+
typeof value.source !== "string" ||
|
|
59
|
+
typeof value.method !== "string" ||
|
|
60
|
+
typeof value.path !== "string" ||
|
|
61
|
+
typeof value.outcome !== "string") {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
called_at: value.calledAt,
|
|
66
|
+
call_kind: value.callKind,
|
|
67
|
+
source: value.source,
|
|
68
|
+
method: value.method,
|
|
69
|
+
api: typeof value.api === "string" ? value.api : null,
|
|
70
|
+
path: value.path,
|
|
71
|
+
outcome: value.outcome,
|
|
72
|
+
request_id: typeof value.requestId === "string" ? value.requestId : null,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
function json(body, status = 200) {
|
|
76
|
+
return HttpServerResponse.jsonUnsafe(body, { status, headers: NO_STORE });
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* The platform's retirement of a departed user's owned connection credentials, called with the
|
|
80
|
+
* request's deployment identity (`DELETE …/owners/:ownerId`) after the action that made them leave
|
|
81
|
+
* committed. A failure, or a request with no deployment identity, is logged and changes nothing
|
|
82
|
+
* else; the next deployment retires what was missed.
|
|
83
|
+
*/
|
|
84
|
+
export function ownedConnectionRetirement(options, identityToken) {
|
|
85
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
86
|
+
const base = `${options.environment.segmentstreamUrl}/api/internal/v1/workspaces/` +
|
|
87
|
+
`${encodeURIComponent(options.environment.workspaceId)}/ontology/connections`;
|
|
88
|
+
return OwnedConnectionRetirement.of({
|
|
89
|
+
retire: (ownerId) => Effect.gen(function* () {
|
|
90
|
+
if (identityToken === undefined || identityToken === "") {
|
|
91
|
+
return yield* Effect.logWarning("ontology.owned_connections.retire_unavailable");
|
|
92
|
+
}
|
|
93
|
+
const status = yield* Effect.tryPromise({
|
|
94
|
+
try: async (signal) => {
|
|
95
|
+
const response = await fetchImpl(`${base}/owners/${encodeURIComponent(ownerId)}`, {
|
|
96
|
+
method: "DELETE",
|
|
97
|
+
redirect: "error",
|
|
98
|
+
headers: {
|
|
99
|
+
accept: "application/json",
|
|
100
|
+
"x-segmentstream-runtime-identity": identityToken,
|
|
101
|
+
"x-segmentstream-organization-id": options.environment.organizationId,
|
|
102
|
+
},
|
|
103
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(BACKEND_TIMEOUT_MS)]),
|
|
104
|
+
});
|
|
105
|
+
await response.body?.cancel();
|
|
106
|
+
return response.status;
|
|
107
|
+
},
|
|
108
|
+
catch: (cause) => cause,
|
|
109
|
+
});
|
|
110
|
+
if (status < 200 || status >= 300) {
|
|
111
|
+
yield* Effect.logWarning("ontology.owned_connections.retire_refused").pipe(Effect.annotateLogs({ status }));
|
|
112
|
+
}
|
|
113
|
+
}).pipe(Effect.catchCause((cause) => Effect.logWarning("ontology.owned_connections.retire_failed", cause))),
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Whether a departed user's owned connection credentials are retired from this service: only in
|
|
118
|
+
* the platform's production deployment (it names its deployment, `workloadTarget`) of an ontology
|
|
119
|
+
* that declares an owned handle. Anywhere else a deactivation, a deletion or an identity
|
|
120
|
+
* revocation calls nothing and reads nothing for it.
|
|
121
|
+
*/
|
|
122
|
+
export function retiresOwnedConnections(input) {
|
|
123
|
+
return input.ownedKeys.size > 0 && !input.preview && input.workloadTarget !== undefined;
|
|
124
|
+
}
|
|
125
|
+
/** Why backend-next did not answer a page of eligible owners. */
|
|
126
|
+
export class EligibleOwnersUnavailable extends Error {
|
|
127
|
+
constructor(message, options) {
|
|
128
|
+
super(message, options);
|
|
129
|
+
this.name = "EligibleOwnersUnavailable";
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
export function eligibleOwners(environment, fetchImpl = fetch) {
|
|
133
|
+
const base = `${environment.segmentstreamUrl}/api/internal/v1/workspaces/` +
|
|
134
|
+
`${encodeURIComponent(environment.workspaceId)}/ontology/connections/owners`;
|
|
135
|
+
return async ({ identityToken, keys, after, requestId }) => {
|
|
136
|
+
const query = new URLSearchParams({ keys: keys.join(",") });
|
|
137
|
+
if (after !== null) {
|
|
138
|
+
query.set("after", after);
|
|
139
|
+
}
|
|
140
|
+
let response;
|
|
141
|
+
try {
|
|
142
|
+
response = await fetchImpl(`${base}?${query.toString()}`, {
|
|
143
|
+
method: "GET",
|
|
144
|
+
redirect: "error",
|
|
145
|
+
headers: {
|
|
146
|
+
accept: "application/json",
|
|
147
|
+
"x-segmentstream-runtime-identity": identityToken,
|
|
148
|
+
"x-segmentstream-organization-id": environment.organizationId,
|
|
149
|
+
"x-segmentstream-request-id": requestId,
|
|
150
|
+
},
|
|
151
|
+
signal: AbortSignal.timeout(BACKEND_TIMEOUT_MS),
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
catch (cause) {
|
|
155
|
+
throw new EligibleOwnersUnavailable("SegmentStream could not be reached.", { cause });
|
|
156
|
+
}
|
|
157
|
+
const text = await response.text();
|
|
158
|
+
let body;
|
|
159
|
+
try {
|
|
160
|
+
body = text === "" ? null : JSON.parse(text);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
body = null;
|
|
164
|
+
}
|
|
165
|
+
if (!response.ok) {
|
|
166
|
+
const code = isRecord(body) && typeof body.error === "string" ? body.error : "unknown";
|
|
167
|
+
throw new EligibleOwnersUnavailable(`SegmentStream refused the eligible owners with ${response.status} (${code}).`);
|
|
168
|
+
}
|
|
169
|
+
if (!isRecord(body) ||
|
|
170
|
+
!Array.isArray(body.owners) ||
|
|
171
|
+
!body.owners.every((owner) => typeof owner === "string") ||
|
|
172
|
+
(body.next !== null && typeof body.next !== "string") ||
|
|
173
|
+
typeof body.ineligible !== "number") {
|
|
174
|
+
throw new EligibleOwnersUnavailable("SegmentStream answered the eligible owners unexpectedly.");
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
owners: body.owners,
|
|
178
|
+
next: body.next,
|
|
179
|
+
ineligible: body.ineligible,
|
|
180
|
+
};
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
export function ownedConnectionsLayer(options) {
|
|
184
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
185
|
+
const base = `${options.environment.segmentstreamUrl}/api/internal/v1/workspaces/` +
|
|
186
|
+
`${encodeURIComponent(options.environment.workspaceId)}/ontology/connections`;
|
|
187
|
+
/**
|
|
188
|
+
* One request to backend-next with the deployment's OIDC token. A refusal backend-next words for
|
|
189
|
+
* the caller (a 4xx other than the runtime's own authentication) is answered as it is; anything
|
|
190
|
+
* else is the platform's fault, logged with its cause and answered as unavailable.
|
|
191
|
+
*/
|
|
192
|
+
const send = (request, call) => Effect.gen(function* () {
|
|
193
|
+
const requestId = yield* RequestId;
|
|
194
|
+
const token = identityToken(request);
|
|
195
|
+
if (token === undefined || token === "") {
|
|
196
|
+
return {
|
|
197
|
+
ok: false,
|
|
198
|
+
response: unavailable(requestId, "Owned connections are available to production deployments, which carry a Vercel " +
|
|
199
|
+
"OIDC token."),
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
const answered = yield* Effect.tryPromise({
|
|
203
|
+
try: async (signal) => {
|
|
204
|
+
const response = await fetchImpl(`${base}${call.path}`, {
|
|
205
|
+
method: call.method,
|
|
206
|
+
redirect: "error",
|
|
207
|
+
headers: {
|
|
208
|
+
accept: "application/json",
|
|
209
|
+
"x-segmentstream-runtime-identity": token,
|
|
210
|
+
"x-segmentstream-organization-id": options.environment.organizationId,
|
|
211
|
+
"x-segmentstream-request-id": requestId,
|
|
212
|
+
...(call.body === undefined ? {} : { "content-type": "application/json" }),
|
|
213
|
+
},
|
|
214
|
+
...(call.body === undefined ? {} : { body: JSON.stringify(call.body) }),
|
|
215
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(BACKEND_TIMEOUT_MS)]),
|
|
216
|
+
});
|
|
217
|
+
const text = await response.text();
|
|
218
|
+
let body = null;
|
|
219
|
+
try {
|
|
220
|
+
body = text === "" ? null : JSON.parse(text);
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
body = null;
|
|
224
|
+
}
|
|
225
|
+
return { status: response.status, body };
|
|
226
|
+
},
|
|
227
|
+
catch: (cause) => cause,
|
|
228
|
+
}).pipe(Effect.map((answer) => ({ _tag: "answered", ...answer })), Effect.catch((cause) => Effect.succeed({ _tag: "unreachable", cause })));
|
|
229
|
+
if (answered._tag === "unreachable") {
|
|
230
|
+
yield* Effect.logError("ontology.owned_connections.unreachable", answered.cause).pipe(Effect.annotateLogs({ requestId }));
|
|
231
|
+
return {
|
|
232
|
+
ok: false,
|
|
233
|
+
response: unavailable(requestId, "SegmentStream could not be reached. Try again."),
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
if (answered.status >= 200 && answered.status < 300) {
|
|
237
|
+
return { ok: true, status: answered.status, body: answered.body };
|
|
238
|
+
}
|
|
239
|
+
const code = isRecord(answered.body) && typeof answered.body.error === "string"
|
|
240
|
+
? answered.body.error
|
|
241
|
+
: undefined;
|
|
242
|
+
const detail = isRecord(answered.body) && typeof answered.body.detail === "string"
|
|
243
|
+
? answered.body.detail
|
|
244
|
+
: undefined;
|
|
245
|
+
if (answered.status >= 400 &&
|
|
246
|
+
answered.status < 500 &&
|
|
247
|
+
answered.status !== 401 &&
|
|
248
|
+
answered.status !== 403 &&
|
|
249
|
+
code !== undefined) {
|
|
250
|
+
return {
|
|
251
|
+
ok: false,
|
|
252
|
+
response: {
|
|
253
|
+
status: answered.status,
|
|
254
|
+
body: {
|
|
255
|
+
error: code,
|
|
256
|
+
detail: detail ?? code,
|
|
257
|
+
requestId,
|
|
258
|
+
...(isRecord(answered.body) && typeof answered.body.retryable === "boolean"
|
|
259
|
+
? { retryable: answered.body.retryable }
|
|
260
|
+
: {}),
|
|
261
|
+
},
|
|
262
|
+
},
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
yield* Effect.logError("ontology.owned_connections.refused").pipe(Effect.annotateLogs({ requestId, status: answered.status, code: code ?? "unknown" }));
|
|
266
|
+
return {
|
|
267
|
+
ok: false,
|
|
268
|
+
response: unavailable(requestId, "SegmentStream could not serve the request. Try again."),
|
|
269
|
+
};
|
|
270
|
+
});
|
|
271
|
+
/** The request's JSON body as an object; `undefined` when it is not one. */
|
|
272
|
+
const bodyOf = (request) => request.json.pipe(Effect.map((value) => (isRecord(value) ? value : undefined)), Effect.catch(() => Effect.succeed(undefined)));
|
|
273
|
+
const keyOf = Effect.map(HttpRouter.params, (params) => {
|
|
274
|
+
const key = params.key ?? "";
|
|
275
|
+
return CONNECTION_KEY.test(key) ? key : undefined;
|
|
276
|
+
});
|
|
277
|
+
return Layer.effectDiscard(Effect.gen(function* () {
|
|
278
|
+
const router = yield* HttpRouter.HttpRouter;
|
|
279
|
+
const backend = yield* OntologyBackend;
|
|
280
|
+
const credential = HttpApiBuilder.securityDecode(HttpApiSecurity.bearer);
|
|
281
|
+
/**
|
|
282
|
+
* A route for the signed-in member only, on their own credential. A guest, a service, a
|
|
283
|
+
* workflow's user and an agent task are refused: none of them is a person who connects. The
|
|
284
|
+
* session cookie authenticates a change only from the app's own origin, as on every route.
|
|
285
|
+
*/
|
|
286
|
+
const asMember = (answer) => (request) => Effect.gen(function* () {
|
|
287
|
+
const bearer = yield* Effect.provideService(credential, HttpServerRequest.HttpServerRequest, request);
|
|
288
|
+
const decided = Effect.gen(function* () {
|
|
289
|
+
const requestId = yield* RequestId;
|
|
290
|
+
const principal = yield* CurrentPrincipal;
|
|
291
|
+
const owner = actingConnectionOwner(principal, yield* currentCaller);
|
|
292
|
+
if (owner === undefined) {
|
|
293
|
+
return toServerResponse(forbidden(requestId, "Only a signed-in member manages their own connections."));
|
|
294
|
+
}
|
|
295
|
+
return yield* answer(request, yield* keyOf, owner.id);
|
|
296
|
+
});
|
|
297
|
+
return yield* withPrincipal(bearer, options.verifyToken, backend, decided, {
|
|
298
|
+
session: { request, exchange: options.exchangeSession },
|
|
299
|
+
});
|
|
300
|
+
});
|
|
301
|
+
const withKey = (requestId, key, answer) => key === undefined
|
|
302
|
+
? Effect.succeed(toServerResponse(notFound(requestId, "There is no such connection.")))
|
|
303
|
+
: answer(key);
|
|
304
|
+
const answerState = (answered, requestId) => {
|
|
305
|
+
if (!answered.ok) {
|
|
306
|
+
return toServerResponse(answered.response);
|
|
307
|
+
}
|
|
308
|
+
const state = stateOf(answered.body);
|
|
309
|
+
return state === undefined
|
|
310
|
+
? toServerResponse(unavailable(requestId, "SegmentStream answered unexpectedly."))
|
|
311
|
+
: json(state);
|
|
312
|
+
};
|
|
313
|
+
// GET: the caller's own owned connections.
|
|
314
|
+
yield* router.add("GET", OWNED_CONNECTIONS_PATH, asMember((request, _key, owner) => Effect.gen(function* () {
|
|
315
|
+
const requestId = yield* RequestId;
|
|
316
|
+
const answered = yield* send(request, {
|
|
317
|
+
method: "GET",
|
|
318
|
+
path: `/owned?${new URLSearchParams({ owner }).toString()}`,
|
|
319
|
+
});
|
|
320
|
+
if (!answered.ok) {
|
|
321
|
+
return toServerResponse(answered.response);
|
|
322
|
+
}
|
|
323
|
+
const listed = isRecord(answered.body) ? answered.body.connections : undefined;
|
|
324
|
+
const connections = Array.isArray(listed) ? listed.map(stateOf) : undefined;
|
|
325
|
+
return connections === undefined || connections.includes(undefined)
|
|
326
|
+
? toServerResponse(unavailable(requestId, "SegmentStream answered unexpectedly."))
|
|
327
|
+
: json({ connections });
|
|
328
|
+
})));
|
|
329
|
+
// GET: the caller's own calls with their credential of the key, newest first.
|
|
330
|
+
yield* router.add("GET", `${OWNED_CONNECTIONS_PATH}/:key/calls`, asMember((request, key, owner) => Effect.gen(function* () {
|
|
331
|
+
const requestId = yield* RequestId;
|
|
332
|
+
return yield* withKey(requestId, key, (key) => Effect.gen(function* () {
|
|
333
|
+
const after = new URL(request.url, "https://ontology.invalid").searchParams.get("after");
|
|
334
|
+
if (after !== null && (after === "" || after.length > MAXIMUM_CURSOR)) {
|
|
335
|
+
return toServerResponse(invalid(requestId, "The cursor is invalid."));
|
|
336
|
+
}
|
|
337
|
+
const query = after === null ? "" : `?${new URLSearchParams({ after })}`;
|
|
338
|
+
const answered = yield* send(request, {
|
|
339
|
+
method: "GET",
|
|
340
|
+
path: `/${key}/owners/${encodeURIComponent(owner)}/calls${query}`,
|
|
341
|
+
});
|
|
342
|
+
if (!answered.ok) {
|
|
343
|
+
return toServerResponse(answered.response);
|
|
344
|
+
}
|
|
345
|
+
const body = isRecord(answered.body) ? answered.body : {};
|
|
346
|
+
const calls = Array.isArray(body.calls) ? body.calls.map(callOf) : undefined;
|
|
347
|
+
return calls === undefined ||
|
|
348
|
+
calls.includes(undefined) ||
|
|
349
|
+
(body.next !== null && typeof body.next !== "string")
|
|
350
|
+
? toServerResponse(unavailable(requestId, "SegmentStream answered unexpectedly."))
|
|
351
|
+
: json({ calls, next: body.next });
|
|
352
|
+
}));
|
|
353
|
+
})));
|
|
354
|
+
// POST: starts the provider's consent for the caller. The consent returns to the app's
|
|
355
|
+
// connections page on its production origin; no caller names where.
|
|
356
|
+
yield* router.add("POST", `${OWNED_CONNECTIONS_PATH}/:key/authorization`, asMember((request, key, owner) => Effect.gen(function* () {
|
|
357
|
+
const requestId = yield* RequestId;
|
|
358
|
+
return yield* withKey(requestId, key, (key) => Effect.gen(function* () {
|
|
359
|
+
const body = yield* bodyOf(request);
|
|
360
|
+
if (body === undefined || typeof body.background !== "boolean") {
|
|
361
|
+
return toServerResponse(invalid(requestId, "Send { background }."));
|
|
362
|
+
}
|
|
363
|
+
const answered = yield* send(request, {
|
|
364
|
+
method: "POST",
|
|
365
|
+
path: `/${key}/authorization`,
|
|
366
|
+
body: { owner, background: body.background },
|
|
367
|
+
});
|
|
368
|
+
if (!answered.ok) {
|
|
369
|
+
return toServerResponse(answered.response);
|
|
370
|
+
}
|
|
371
|
+
const started = isRecord(answered.body) ? answered.body : {};
|
|
372
|
+
return typeof started.authorizationUrl !== "string" ||
|
|
373
|
+
typeof started.expiresAt !== "string"
|
|
374
|
+
? toServerResponse(unavailable(requestId, "SegmentStream answered unexpectedly."))
|
|
375
|
+
: json({
|
|
376
|
+
authorization_url: started.authorizationUrl,
|
|
377
|
+
expires_at: started.expiresAt,
|
|
378
|
+
});
|
|
379
|
+
}));
|
|
380
|
+
})));
|
|
381
|
+
// POST: connects the caller with a token they supply, for a provider that admits one.
|
|
382
|
+
yield* router.add("POST", `${OWNED_CONNECTIONS_PATH}/:key/authorization/token`, asMember((request, key, owner) => Effect.gen(function* () {
|
|
383
|
+
const requestId = yield* RequestId;
|
|
384
|
+
return yield* withKey(requestId, key, (key) => Effect.gen(function* () {
|
|
385
|
+
const body = yield* bodyOf(request);
|
|
386
|
+
if (body === undefined ||
|
|
387
|
+
typeof body.background !== "boolean" ||
|
|
388
|
+
typeof body.token !== "string" ||
|
|
389
|
+
body.token === "" ||
|
|
390
|
+
body.token.length > MAXIMUM_TOKEN ||
|
|
391
|
+
(body.account_id !== undefined &&
|
|
392
|
+
(typeof body.account_id !== "string" ||
|
|
393
|
+
body.account_id.length > MAXIMUM_ACCOUNT))) {
|
|
394
|
+
return toServerResponse(invalid(requestId, "Send { token, background } and an optional account_id."));
|
|
395
|
+
}
|
|
396
|
+
return answerState(yield* send(request, {
|
|
397
|
+
method: "POST",
|
|
398
|
+
path: `/${key}/authorization/token`,
|
|
399
|
+
body: {
|
|
400
|
+
owner,
|
|
401
|
+
token: body.token,
|
|
402
|
+
background: body.background,
|
|
403
|
+
...(body.account_id === undefined ? {} : { accountId: body.account_id }),
|
|
404
|
+
},
|
|
405
|
+
}), requestId);
|
|
406
|
+
}));
|
|
407
|
+
})));
|
|
408
|
+
// POST: the caller, back from the provider, confirms the code the page read from its
|
|
409
|
+
// fragment. backend-next activates the credential only for the attempt's own owner.
|
|
410
|
+
yield* router.add("POST", `${OWNED_CONNECTIONS_PATH}/:key/authorization/confirm`, asMember((request, key, owner) => Effect.gen(function* () {
|
|
411
|
+
const requestId = yield* RequestId;
|
|
412
|
+
return yield* withKey(requestId, key, (key) => Effect.gen(function* () {
|
|
413
|
+
const body = yield* bodyOf(request);
|
|
414
|
+
if (body === undefined ||
|
|
415
|
+
typeof body.confirmation !== "string" ||
|
|
416
|
+
body.confirmation === "" ||
|
|
417
|
+
body.confirmation.length > MAXIMUM_CONFIRMATION) {
|
|
418
|
+
return toServerResponse(invalid(requestId, "Send { confirmation }."));
|
|
419
|
+
}
|
|
420
|
+
return answerState(yield* send(request, {
|
|
421
|
+
method: "POST",
|
|
422
|
+
path: `/${key}/authorization/confirm`,
|
|
423
|
+
body: { owner, confirmation: body.confirmation },
|
|
424
|
+
}), requestId);
|
|
425
|
+
}));
|
|
426
|
+
})));
|
|
427
|
+
// POST, with no credential: spends a code the page could not confirm because nobody is
|
|
428
|
+
// signed in, so its secret is deleted. It names no owner, can never activate a credential
|
|
429
|
+
// and answers the same whether or not the code matched; a browser may send it only from the
|
|
430
|
+
// app's own pages. A key that is not an owned handle, or a body that is not a code, has no
|
|
431
|
+
// code to spend: it is answered as a discarded one without asking backend-next, so the route
|
|
432
|
+
// neither tells which keys are owned nor turns anonymous requests into backend load.
|
|
433
|
+
yield* router.add("POST", `${OWNED_CONNECTIONS_PATH}/:key/authorization/discard`, (request) => Effect.gen(function* () {
|
|
434
|
+
const requestId = yield* RequestId;
|
|
435
|
+
const discarded = HttpServerResponse.empty({ status: 204, headers: NO_STORE });
|
|
436
|
+
if (crossSiteRequest(request)) {
|
|
437
|
+
return toServerResponse(forbidden(requestId, "A confirmation is discarded only from the app's own pages."));
|
|
438
|
+
}
|
|
439
|
+
// No rate limit: the starter calls this route from its own server, so every person
|
|
440
|
+
// would share one client address, and a discard spends only a code its caller holds.
|
|
441
|
+
const key = yield* keyOf;
|
|
442
|
+
if (key === undefined || !options.ownedKeys.has(key)) {
|
|
443
|
+
return discarded;
|
|
444
|
+
}
|
|
445
|
+
const body = yield* bodyOf(request);
|
|
446
|
+
if (body === undefined ||
|
|
447
|
+
typeof body.confirmation !== "string" ||
|
|
448
|
+
body.confirmation === "" ||
|
|
449
|
+
body.confirmation.length > MAXIMUM_CONFIRMATION) {
|
|
450
|
+
return discarded;
|
|
451
|
+
}
|
|
452
|
+
const answered = yield* send(request, {
|
|
453
|
+
method: "POST",
|
|
454
|
+
path: `/${key}/authorization/discard`,
|
|
455
|
+
body: { confirmation: body.confirmation },
|
|
456
|
+
});
|
|
457
|
+
return answered.ok ? discarded : toServerResponse(answered.response);
|
|
458
|
+
}));
|
|
459
|
+
// PATCH: sets or clears the caller's background consent on their own credential.
|
|
460
|
+
yield* router.add("PATCH", `${OWNED_CONNECTIONS_PATH}/:key`, asMember((request, key, owner) => Effect.gen(function* () {
|
|
461
|
+
const requestId = yield* RequestId;
|
|
462
|
+
return yield* withKey(requestId, key, (key) => Effect.gen(function* () {
|
|
463
|
+
const body = yield* bodyOf(request);
|
|
464
|
+
if (body === undefined || typeof body.background !== "boolean") {
|
|
465
|
+
return toServerResponse(invalid(requestId, "Send { background }."));
|
|
466
|
+
}
|
|
467
|
+
return answerState(yield* send(request, {
|
|
468
|
+
method: "PATCH",
|
|
469
|
+
path: `/${key}/owners/${encodeURIComponent(owner)}`,
|
|
470
|
+
body: { background: body.background },
|
|
471
|
+
}), requestId);
|
|
472
|
+
}));
|
|
473
|
+
})));
|
|
474
|
+
// DELETE: disconnects the caller's own credential of the key.
|
|
475
|
+
yield* router.add("DELETE", `${OWNED_CONNECTIONS_PATH}/:key`, asMember((request, key, owner) => Effect.gen(function* () {
|
|
476
|
+
const requestId = yield* RequestId;
|
|
477
|
+
return yield* withKey(requestId, key, (key) => Effect.gen(function* () {
|
|
478
|
+
const answered = yield* send(request, {
|
|
479
|
+
method: "DELETE",
|
|
480
|
+
path: `/owners/${encodeURIComponent(owner)}?${new URLSearchParams({ key })}`,
|
|
481
|
+
});
|
|
482
|
+
return answered.ok
|
|
483
|
+
? HttpServerResponse.empty({ status: 204, headers: NO_STORE })
|
|
484
|
+
: toServerResponse(answered.response);
|
|
485
|
+
}));
|
|
486
|
+
})));
|
|
487
|
+
}));
|
|
488
|
+
}
|
|
@@ -514,6 +514,11 @@ export interface ResolveIdentityInput {
|
|
|
514
514
|
readonly provider: string;
|
|
515
515
|
readonly externalId: string;
|
|
516
516
|
readonly chat: "private" | "group";
|
|
517
|
+
/** Trusted delivery address from the verified channel update. */
|
|
518
|
+
readonly delivery?: {
|
|
519
|
+
readonly channel: string;
|
|
520
|
+
readonly chatId: string;
|
|
521
|
+
};
|
|
517
522
|
readonly turn: boolean;
|
|
518
523
|
readonly display?: string | null;
|
|
519
524
|
readonly username?: string;
|
|
@@ -566,6 +571,7 @@ export type AgentResolution = {
|
|
|
566
571
|
readonly takeover?: true;
|
|
567
572
|
} | {
|
|
568
573
|
readonly status: "pairing_required";
|
|
574
|
+
readonly telegramMiniApp?: true;
|
|
569
575
|
} | {
|
|
570
576
|
readonly status: "refused";
|
|
571
577
|
readonly reason: "blocked" | "inactive";
|
|
@@ -622,6 +628,10 @@ export interface AgentStore {
|
|
|
622
628
|
readonly codeHash: string;
|
|
623
629
|
}) => Effect.Effect<boolean>;
|
|
624
630
|
/** A pairing that has neither expired nor been approved. */
|
|
631
|
+
/** The hash stays inside the service. A public launch id alone cannot approve a pairing. */
|
|
632
|
+
readonly telegramLaunchPairing?: (id: string, sender: string) => Effect.Effect<{
|
|
633
|
+
readonly codeHash: string;
|
|
634
|
+
} | undefined>;
|
|
625
635
|
readonly findPairing: (codeHash: string) => Effect.Effect<AgentPairing | undefined>;
|
|
626
636
|
/**
|
|
627
637
|
* Consumes a live pairing once. The same account on the same member is idempotent; another
|
|
@@ -635,6 +645,8 @@ export interface AgentStore {
|
|
|
635
645
|
}) => Effect.Effect<AgentIdentity | undefined, IdentityInUse>;
|
|
636
646
|
/** Finds an active identity, or provisions a private sender when the channel admits strangers. */
|
|
637
647
|
readonly resolveIdentity: (input: ResolveIdentityInput) => Effect.Effect<AgentResolution>;
|
|
648
|
+
/** Optional inbound admission handlers keyed by messenger provider. Each may delegate to resolveIdentity. */
|
|
649
|
+
readonly inboundIdentity?: ReadonlyMap<string, AgentStore["resolveIdentity"]>;
|
|
638
650
|
/** Complete the leased limit-reply claim only after delivery, or release it after failure. */
|
|
639
651
|
readonly completeLimitNotice: (input: {
|
|
640
652
|
readonly notificationId: string;
|
|
@@ -967,6 +979,8 @@ declare const OntologyBackend_base: Context.ServiceClass<OntologyBackend, "@segm
|
|
|
967
979
|
readonly requestId: string;
|
|
968
980
|
/** The recovery run's horizon: count as waiting only the rows created before it. */
|
|
969
981
|
readonly before?: string | undefined;
|
|
982
|
+
/** Epoch ms: sweep batch after batch until this instant, launching no start after it. */
|
|
983
|
+
readonly deadline?: number | undefined;
|
|
970
984
|
}) => Effect.Effect<SweepResult>;
|
|
971
985
|
readonly list: (input: {
|
|
972
986
|
/** The workflow's wire name. */
|
|
@@ -976,6 +990,18 @@ declare const OntologyBackend_base: Context.ServiceClass<OntologyBackend, "@segm
|
|
|
976
990
|
readonly limit: number;
|
|
977
991
|
readonly after?: string | undefined;
|
|
978
992
|
}) => Effect.Effect<WorkflowStartsPage, InvalidStartsCursor>;
|
|
993
|
+
/**
|
|
994
|
+
* Writes the pending rows a cron decided for the owners of an owned workflow, one per owner
|
|
995
|
+
* and scheduled minute, and answers how many were new. Absent on a backend that cannot.
|
|
996
|
+
*/
|
|
997
|
+
readonly writeOwned?: (starts: ReadonlyArray<import("../runtime/workflow-starts.js").OwnedCronStart>) => Effect.Effect<number>;
|
|
998
|
+
/** Starts the pending rows of one cron fire until `deadline`, as a sweep starts rows. */
|
|
999
|
+
readonly startFired?: (input: {
|
|
1000
|
+
readonly trigger: string;
|
|
1001
|
+
readonly fireKey: string;
|
|
1002
|
+
readonly requestId: string;
|
|
1003
|
+
readonly deadline: number;
|
|
1004
|
+
}) => Effect.Effect<import("../runtime/workflow-starts.js").FiredStarts>;
|
|
979
1005
|
};
|
|
980
1006
|
/** The tasks workflows hand the app's agent, in `_agent_tasks`. */
|
|
981
1007
|
readonly agentTasks?: AgentTaskStore;
|
|
@@ -1021,6 +1047,14 @@ declare const OntologyBackend_base: Context.ServiceClass<OntologyBackend, "@segm
|
|
|
1021
1047
|
readonly workspaceId: string;
|
|
1022
1048
|
readonly workflow: string;
|
|
1023
1049
|
}) => Effect.Effect<Principal | undefined>;
|
|
1050
|
+
/**
|
|
1051
|
+
* The owner a workflow run acts as: the member `userId` names, with the roles, permissions and
|
|
1052
|
+
* scopes they hold now. `undefined` once they are inactive, blocked or deleted, or are not a
|
|
1053
|
+
* member. No token resolves it; only a run's recorded owner names it.
|
|
1054
|
+
*/
|
|
1055
|
+
readonly resolveRunOwner?: (userId: string) => Effect.Effect<Principal | undefined>;
|
|
1056
|
+
/** Of the user ids given, those of active members, who may own a run a cron starts. */
|
|
1057
|
+
readonly activeMembers?: (userIds: ReadonlyArray<string>) => Effect.Effect<ReadonlySet<string>>;
|
|
1024
1058
|
/**
|
|
1025
1059
|
* Finds, links or creates the member's user. `undefined` when the user may not sign in, and
|
|
1026
1060
|
* {@link NotInvited} when the sign-in policy turns away a person nobody invited.
|
|
@@ -531,6 +531,7 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
|
|
|
531
531
|
readonly key: Schema.String;
|
|
532
532
|
readonly description: Schema.String;
|
|
533
533
|
readonly delivers: Schema.optionalKey<Schema.Literal<true>>;
|
|
534
|
+
readonly owner: Schema.optionalKey<Schema.Literal<"user">>;
|
|
534
535
|
}>>>;
|
|
535
536
|
readonly chat: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
|
|
536
537
|
readonly telegram: Schema.optionalKey<Schema.Struct<{
|
|
@@ -926,6 +927,7 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
|
|
|
926
927
|
readonly key: Schema.String;
|
|
927
928
|
readonly description: Schema.String;
|
|
928
929
|
readonly delivers: Schema.optionalKey<Schema.Literal<true>>;
|
|
930
|
+
readonly owner: Schema.optionalKey<Schema.Literal<"user">>;
|
|
929
931
|
}>>>>;
|
|
930
932
|
readonly chat: Schema.toEncoded<Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
|
|
931
933
|
readonly telegram: Schema.optionalKey<Schema.Struct<{
|
package/dist/service/service.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { telegramPairingLayer } from "./channel/telegram-pairing.js";
|
|
1
2
|
import { Cause, Context, Effect, Layer, Redacted } from "effect";
|
|
2
3
|
import { HttpRouter, HttpServer, HttpServerError, HttpServerRequest } from "effect/unstable/http";
|
|
3
4
|
import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
|
|
@@ -17,6 +18,7 @@ import { implicitMemberOf } from "../role.js";
|
|
|
17
18
|
import { sqlServiceRuntime } from "../runtime/service-binding.js";
|
|
18
19
|
import { neonSignInLinks, segmentstreamSignInLinks } from "../runtime/sign-in-links.js";
|
|
19
20
|
import { memberFileRoutes } from "./member-file-routes.js";
|
|
21
|
+
import { eligibleOwners, ownedConnectionRetirement, ownedConnectionsLayer, retiresOwnedConnections, } from "./owned-connections.js";
|
|
20
22
|
import { attachmentsLayer } from "./agent/attachments.js";
|
|
21
23
|
import { filesLayer } from "./agent/files.js";
|
|
22
24
|
import { workspaceSourceLayer } from "./agent/source.js";
|
|
@@ -372,6 +374,15 @@ export function createOntologyService(ontology, config) {
|
|
|
372
374
|
}
|
|
373
375
|
: {}),
|
|
374
376
|
});
|
|
377
|
+
// The keys the deployed ontology declares owned on a handle: one credential for each user.
|
|
378
|
+
const ownedKeys = new Set((ontology.manifest.connections ?? [])
|
|
379
|
+
.filter((candidate) => candidate.owner === "user")
|
|
380
|
+
.map((candidate) => candidate.key));
|
|
381
|
+
const retiresOwned = retiresOwnedConnections({
|
|
382
|
+
ownedKeys,
|
|
383
|
+
preview,
|
|
384
|
+
workloadTarget: config.workloadTarget,
|
|
385
|
+
});
|
|
375
386
|
const connections = preview
|
|
376
387
|
? () => ({
|
|
377
388
|
request: () => Effect.die(new DeploymentAdmissionError("preview_capability_unavailable", "connections")),
|
|
@@ -379,7 +390,11 @@ export function createOntologyService(ontology, config) {
|
|
|
379
390
|
})
|
|
380
391
|
: (config.connections ??
|
|
381
392
|
(config.localConnections === undefined
|
|
382
|
-
?
|
|
393
|
+
? retiresOwned
|
|
394
|
+
? Object.assign(deployedConnections(config), {
|
|
395
|
+
retirement: (token) => ownedConnectionRetirement({ environment: config, fetch: config.ownedConnectionsFetch }, token),
|
|
396
|
+
})
|
|
397
|
+
: deployedConnections(config)
|
|
383
398
|
: localConnections(config.localConnections)));
|
|
384
399
|
const replicate = deployedReplication(config);
|
|
385
400
|
// The platform keeps chat history for production agents only.
|
|
@@ -515,6 +530,8 @@ export function createOntologyService(ontology, config) {
|
|
|
515
530
|
});
|
|
516
531
|
const application = Layer.mergeAll(channelApps.length > 0
|
|
517
532
|
? Layer.merge(channelSessionLayer(config), channelSignInLayer(channelApps, config, connections))
|
|
533
|
+
: Layer.empty, !preview && telegram?.miniApp && telegramConnection && federationConfig
|
|
534
|
+
? telegramPairingLayer(config, connections, telegramAppProvider(telegramConnection, testKey), telegramConnection, verifyToken)
|
|
518
535
|
: Layer.empty, federationLayer(federationConfig, verifyToken, { ontology, browserRevision }), routes, withoutAgent
|
|
519
536
|
? Layer.empty
|
|
520
537
|
: chatRoutes({
|
|
@@ -535,7 +552,13 @@ export function createOntologyService(ontology, config) {
|
|
|
535
552
|
chatDelivery,
|
|
536
553
|
verifyToken,
|
|
537
554
|
exchangeSession,
|
|
538
|
-
}), withoutAgent ? Layer.empty : filesLayer({ plan: built.plan, verifyRuntime }),
|
|
555
|
+
}), withoutAgent ? Layer.empty : filesLayer({ plan: built.plan, verifyRuntime }), ownedConnectionsLayer({
|
|
556
|
+
environment: config,
|
|
557
|
+
ownedKeys,
|
|
558
|
+
verifyToken,
|
|
559
|
+
exchangeSession,
|
|
560
|
+
fetch: config.ownedConnectionsFetch,
|
|
561
|
+
}), preview ? Layer.empty : workspaceSourceLayer({ environment: config, verifyRuntime }), chatHistory === undefined
|
|
539
562
|
? Layer.empty
|
|
540
563
|
: archiveRoutes({
|
|
541
564
|
transport: chatHistory,
|
|
@@ -558,6 +581,7 @@ export function createOntologyService(ontology, config) {
|
|
|
558
581
|
engine: workflowEngine,
|
|
559
582
|
agentOrigin: config.agentOrigin,
|
|
560
583
|
agentTransport: config.agentTaskTransport,
|
|
584
|
+
eligibleOwners: eligibleOwners(config, config.ownedConnectionsFetch),
|
|
561
585
|
webhookSecret: config.webhookSecret,
|
|
562
586
|
webhookVerifier: config.webhookVerifier ??
|
|
563
587
|
deployedWebhookVerifier({
|