@agentjam/sdk 0.0.0-stage → 0.1.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/README.md +181 -2
- package/dist/adapters/ai.d.ts +47 -0
- package/dist/adapters/ai.d.ts.map +1 -0
- package/dist/adapters/ai.js +168 -0
- package/dist/adapters/ai.js.map +1 -0
- package/dist/adapters/anthropic.d.ts +68 -0
- package/dist/adapters/anthropic.d.ts.map +1 -0
- package/dist/adapters/anthropic.js +193 -0
- package/dist/adapters/anthropic.js.map +1 -0
- package/dist/adapters/openai.d.ts +35 -0
- package/dist/adapters/openai.d.ts.map +1 -0
- package/dist/adapters/openai.js +80 -0
- package/dist/adapters/openai.js.map +1 -0
- package/dist/adapters/openaiAgents.d.ts +39 -0
- package/dist/adapters/openaiAgents.d.ts.map +1 -0
- package/dist/adapters/openaiAgents.js +152 -0
- package/dist/adapters/openaiAgents.js.map +1 -0
- package/dist/adapters/shared.d.ts +72 -0
- package/dist/adapters/shared.d.ts.map +1 -0
- package/dist/adapters/shared.js +174 -0
- package/dist/adapters/shared.js.map +1 -0
- package/dist/agent.d.ts +462 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +1820 -0
- package/dist/agent.js.map +1 -0
- package/dist/artifacts.d.ts +79 -0
- package/dist/artifacts.d.ts.map +1 -0
- package/dist/artifacts.js +367 -0
- package/dist/artifacts.js.map +1 -0
- package/dist/attachments.d.ts +43 -0
- package/dist/attachments.d.ts.map +1 -0
- package/dist/attachments.js +69 -0
- package/dist/attachments.js.map +1 -0
- package/dist/connections.d.ts +109 -0
- package/dist/connections.d.ts.map +1 -0
- package/dist/connections.js +274 -0
- package/dist/connections.js.map +1 -0
- package/dist/content.d.ts +36 -0
- package/dist/content.d.ts.map +1 -0
- package/dist/content.js +21 -0
- package/dist/content.js.map +1 -0
- package/dist/cron.d.ts +31 -0
- package/dist/cron.d.ts.map +1 -0
- package/dist/cron.js +93 -0
- package/dist/cron.js.map +1 -0
- package/dist/errors.d.ts +227 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +253 -0
- package/dist/errors.js.map +1 -0
- package/dist/events.d.ts +57 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +24 -0
- package/dist/events.js.map +1 -0
- package/dist/idempotency.d.ts +21 -0
- package/dist/idempotency.d.ts.map +1 -0
- package/dist/idempotency.js +46 -0
- package/dist/idempotency.js.map +1 -0
- package/dist/index.d.ts +44 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +18 -0
- package/dist/index.js.map +1 -0
- package/dist/inputs.d.ts +22 -0
- package/dist/inputs.d.ts.map +1 -0
- package/dist/inputs.js +72 -0
- package/dist/inputs.js.map +1 -0
- package/dist/mpp.d.ts +76 -0
- package/dist/mpp.d.ts.map +1 -0
- package/dist/mpp.js +113 -0
- package/dist/mpp.js.map +1 -0
- package/dist/oauth.d.ts +3 -0
- package/dist/oauth.d.ts.map +1 -0
- package/dist/oauth.js +2 -0
- package/dist/oauth.js.map +1 -0
- package/dist/oauthCallbacks.d.ts +2 -0
- package/dist/oauthCallbacks.d.ts.map +1 -0
- package/dist/oauthCallbacks.js +58 -0
- package/dist/oauthCallbacks.js.map +1 -0
- package/dist/platforms/datadog.d.ts +10 -0
- package/dist/platforms/datadog.d.ts.map +1 -0
- package/dist/platforms/datadog.js +15 -0
- package/dist/platforms/datadog.js.map +1 -0
- package/dist/platforms/github.d.ts +181 -0
- package/dist/platforms/github.d.ts.map +1 -0
- package/dist/platforms/github.js +468 -0
- package/dist/platforms/github.js.map +1 -0
- package/dist/platforms/google.d.ts +19 -0
- package/dist/platforms/google.d.ts.map +1 -0
- package/dist/platforms/google.js +70 -0
- package/dist/platforms/google.js.map +1 -0
- package/dist/platforms/grafana.d.ts +10 -0
- package/dist/platforms/grafana.d.ts.map +1 -0
- package/dist/platforms/grafana.js +14 -0
- package/dist/platforms/grafana.js.map +1 -0
- package/dist/platforms/posthog.d.ts +10 -0
- package/dist/platforms/posthog.d.ts.map +1 -0
- package/dist/platforms/posthog.js +14 -0
- package/dist/platforms/posthog.js.map +1 -0
- package/dist/platforms/presets.d.ts +34 -0
- package/dist/platforms/presets.d.ts.map +1 -0
- package/dist/platforms/presets.js +36 -0
- package/dist/platforms/presets.js.map +1 -0
- package/dist/platforms/sentry.d.ts +79 -0
- package/dist/platforms/sentry.d.ts.map +1 -0
- package/dist/platforms/sentry.js +124 -0
- package/dist/platforms/sentry.js.map +1 -0
- package/dist/platforms/slack.d.ts +101 -0
- package/dist/platforms/slack.d.ts.map +1 -0
- package/dist/platforms/slack.js +309 -0
- package/dist/platforms/slack.js.map +1 -0
- package/dist/platforms/splunk.d.ts +10 -0
- package/dist/platforms/splunk.d.ts.map +1 -0
- package/dist/platforms/splunk.js +14 -0
- package/dist/platforms/splunk.js.map +1 -0
- package/dist/polling.d.ts +2 -0
- package/dist/polling.d.ts.map +1 -0
- package/dist/polling.js +66 -0
- package/dist/polling.js.map +1 -0
- package/dist/profile.d.ts +60 -0
- package/dist/profile.d.ts.map +1 -0
- package/dist/profile.js +119 -0
- package/dist/profile.js.map +1 -0
- package/dist/protocol.d.ts +474 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +2 -0
- package/dist/protocol.js.map +1 -0
- package/dist/providers.d.ts +113 -0
- package/dist/providers.d.ts.map +1 -0
- package/dist/providers.js +98 -0
- package/dist/providers.js.map +1 -0
- package/dist/recaps.d.ts +10 -0
- package/dist/recaps.d.ts.map +1 -0
- package/dist/recaps.js +49 -0
- package/dist/recaps.js.map +1 -0
- package/dist/relay/chains.d.ts +62 -0
- package/dist/relay/chains.d.ts.map +1 -0
- package/dist/relay/chains.js +150 -0
- package/dist/relay/chains.js.map +1 -0
- package/dist/relay/credentials.d.ts +25 -0
- package/dist/relay/credentials.d.ts.map +1 -0
- package/dist/relay/credentials.js +234 -0
- package/dist/relay/credentials.js.map +1 -0
- package/dist/relay/endpoints.d.ts +13 -0
- package/dist/relay/endpoints.d.ts.map +1 -0
- package/dist/relay/endpoints.js +13 -0
- package/dist/relay/endpoints.js.map +1 -0
- package/dist/relay/frames.d.ts +193 -0
- package/dist/relay/frames.d.ts.map +1 -0
- package/dist/relay/frames.js +161 -0
- package/dist/relay/frames.js.map +1 -0
- package/dist/relay/grants.d.ts +158 -0
- package/dist/relay/grants.d.ts.map +1 -0
- package/dist/relay/grants.js +2 -0
- package/dist/relay/grants.js.map +1 -0
- package/dist/relay/guestStore.d.ts +37 -0
- package/dist/relay/guestStore.d.ts.map +1 -0
- package/dist/relay/guestStore.js +61 -0
- package/dist/relay/guestStore.js.map +1 -0
- package/dist/relay/guests.d.ts +7 -0
- package/dist/relay/guests.d.ts.map +1 -0
- package/dist/relay/guests.js +30 -0
- package/dist/relay/guests.js.map +1 -0
- package/dist/relay/memory.d.ts +60 -0
- package/dist/relay/memory.d.ts.map +1 -0
- package/dist/relay/memory.js +334 -0
- package/dist/relay/memory.js.map +1 -0
- package/dist/relay/payments.d.ts +43 -0
- package/dist/relay/payments.d.ts.map +1 -0
- package/dist/relay/payments.js +115 -0
- package/dist/relay/payments.js.map +1 -0
- package/dist/relay/profiles.d.ts +10 -0
- package/dist/relay/profiles.d.ts.map +1 -0
- package/dist/relay/profiles.js +43 -0
- package/dist/relay/profiles.js.map +1 -0
- package/dist/relay/relay.d.ts +133 -0
- package/dist/relay/relay.d.ts.map +1 -0
- package/dist/relay/relay.js +2 -0
- package/dist/relay/relay.js.map +1 -0
- package/dist/relay/remote.d.ts +39 -0
- package/dist/relay/remote.d.ts.map +1 -0
- package/dist/relay/remote.js +492 -0
- package/dist/relay/remote.js.map +1 -0
- package/dist/relay/revisions.d.ts +13 -0
- package/dist/relay/revisions.d.ts.map +1 -0
- package/dist/relay/revisions.js +34 -0
- package/dist/relay/revisions.js.map +1 -0
- package/dist/relay/schedules.d.ts +41 -0
- package/dist/relay/schedules.d.ts.map +1 -0
- package/dist/relay/schedules.js +217 -0
- package/dist/relay/schedules.js.map +1 -0
- package/dist/relay/secrets.d.ts +14 -0
- package/dist/relay/secrets.d.ts.map +1 -0
- package/dist/relay/secrets.js +30 -0
- package/dist/relay/secrets.js.map +1 -0
- package/dist/relay/sessions.d.ts +59 -0
- package/dist/relay/sessions.d.ts.map +1 -0
- package/dist/relay/sessions.js +282 -0
- package/dist/relay/sessions.js.map +1 -0
- package/dist/relay/uploads.d.ts +15 -0
- package/dist/relay/uploads.d.ts.map +1 -0
- package/dist/relay/uploads.js +55 -0
- package/dist/relay/uploads.js.map +1 -0
- package/dist/requests.d.ts +22 -0
- package/dist/requests.d.ts.map +1 -0
- package/dist/requests.js +64 -0
- package/dist/requests.js.map +1 -0
- package/dist/screening.d.ts +93 -0
- package/dist/screening.d.ts.map +1 -0
- package/dist/screening.js +176 -0
- package/dist/screening.js.map +1 -0
- package/dist/secrets.d.ts +38 -0
- package/dist/secrets.d.ts.map +1 -0
- package/dist/secrets.js +162 -0
- package/dist/secrets.js.map +1 -0
- package/dist/skills.d.ts +11 -0
- package/dist/skills.d.ts.map +1 -0
- package/dist/skills.js +55 -0
- package/dist/skills.js.map +1 -0
- package/dist/stripe.d.ts +10 -0
- package/dist/stripe.d.ts.map +1 -0
- package/dist/stripe.js +51 -0
- package/dist/stripe.js.map +1 -0
- package/dist/tasks/access.d.ts +35 -0
- package/dist/tasks/access.d.ts.map +1 -0
- package/dist/tasks/access.js +101 -0
- package/dist/tasks/access.js.map +1 -0
- package/dist/tasks/incoming.d.ts +333 -0
- package/dist/tasks/incoming.d.ts.map +1 -0
- package/dist/tasks/incoming.js +354 -0
- package/dist/tasks/incoming.js.map +1 -0
- package/dist/tasks/outgoing.d.ts +137 -0
- package/dist/tasks/outgoing.d.ts.map +1 -0
- package/dist/tasks/outgoing.js +233 -0
- package/dist/tasks/outgoing.js.map +1 -0
- package/dist/tasks/scheduled.d.ts +76 -0
- package/dist/tasks/scheduled.d.ts.map +1 -0
- package/dist/tasks/scheduled.js +110 -0
- package/dist/tasks/scheduled.js.map +1 -0
- package/dist/tasks/triggers.d.ts +47 -0
- package/dist/tasks/triggers.d.ts.map +1 -0
- package/dist/tasks/triggers.js +149 -0
- package/dist/tasks/triggers.js.map +1 -0
- package/dist/tasks/watches.d.ts +13 -0
- package/dist/tasks/watches.d.ts.map +1 -0
- package/dist/tasks/watches.js +54 -0
- package/dist/tasks/watches.js.map +1 -0
- package/dist/tools.d.ts +85 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/tools.js +627 -0
- package/dist/tools.js.map +1 -0
- package/dist/types.d.ts +926 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/vaults/local.d.ts +54 -0
- package/dist/vaults/local.d.ts.map +1 -0
- package/dist/vaults/local.js +362 -0
- package/dist/vaults/local.js.map +1 -0
- package/dist/vaults/remote.d.ts +78 -0
- package/dist/vaults/remote.d.ts.map +1 -0
- package/dist/vaults/remote.js +295 -0
- package/dist/vaults/remote.js.map +1 -0
- package/dist/vaults/vault.d.ts +69 -0
- package/dist/vaults/vault.d.ts.map +1 -0
- package/dist/vaults/vault.js +19 -0
- package/dist/vaults/vault.js.map +1 -0
- package/dist/verdicts.d.ts +15 -0
- package/dist/verdicts.d.ts.map +1 -0
- package/dist/verdicts.js +17 -0
- package/dist/verdicts.js.map +1 -0
- package/dist/watermarks.d.ts +29 -0
- package/dist/watermarks.d.ts.map +1 -0
- package/dist/watermarks.js +11 -0
- package/dist/watermarks.js.map +1 -0
- package/package.json +152 -3
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import type { ConnectionHolder } from "../connections.js";
|
|
2
|
+
import type { AgentJamError } from "../errors.js";
|
|
3
|
+
import type { Envelope, EnvelopeDraft, TaskRecapRef, TaskRef } from "../protocol.js";
|
|
4
|
+
import type { AgentCard, AgentQuery, AutoReloadSettings, ConnectionFetch, CreditAccount, Dispute, HistoryPage, HistoryQuery, ProfileUpdate, Review, ReviewDraft, ReviewPage, ReviewQuery, StoredAgent, TaskPage, TaskQuery, TriggerSchedule } from "../types.js";
|
|
5
|
+
import type { OAuthChannel } from "./grants.js";
|
|
6
|
+
/** What a relay reports about an agent's session besides its envelopes. Relays that never lose a session can ignore these. */
|
|
7
|
+
export type SessionEvents = {
|
|
8
|
+
/** Called once a relay that ended the agent's session during an outage has connected it under a new one. Peers were told the agent left, so the work it ran won't resume, but the tasks it delegated keep running. */
|
|
9
|
+
onSessionReplaced?: () => void;
|
|
10
|
+
/** Called when the connection fails for good, such as when another connection takes over the agent's name. */
|
|
11
|
+
onError?: (error: AgentJamError) => void;
|
|
12
|
+
};
|
|
13
|
+
/** How a connection joins the agent's other sessions. */
|
|
14
|
+
export type SessionOptions = {
|
|
15
|
+
/** Names this process, so only one connection per instance runs at a time. Leave it out to run every process as its own session. */
|
|
16
|
+
instanceId?: string | undefined;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Routes envelopes between connected agents. Implement this to plug in a custom transport.
|
|
20
|
+
*
|
|
21
|
+
* A relay stamps each envelope with its sender's name, delivers envelopes in per-sender order, and
|
|
22
|
+
* attaches the conversation's answered turns to each message as `history`. An agent may hold many
|
|
23
|
+
* sessions at once: new work goes to one of them, and every follow-up to the session that took it.
|
|
24
|
+
* When a session leaves, the relay sends a `disconnect` from it to the sessions it was working with.
|
|
25
|
+
*
|
|
26
|
+
* Durable relays may store envelopes and deliver them more than once. Agents deduplicate repeated
|
|
27
|
+
* ids for a short window, so a relay that remembers longer should answer an old repeated request
|
|
28
|
+
* from the stored response, then replay the task's envelopes in order.
|
|
29
|
+
*/
|
|
30
|
+
export interface Relay {
|
|
31
|
+
/**
|
|
32
|
+
* Stores a new agent, filling in the fields `profile` leaves out with an empty profile.
|
|
33
|
+
*
|
|
34
|
+
* @throws AgentExistsError if an agent with that name already exists.
|
|
35
|
+
*/
|
|
36
|
+
create(name: string, profile: ProfileUpdate): Promise<StoredAgent>;
|
|
37
|
+
/**
|
|
38
|
+
* Changes only the fields of the agent's stored profile that `profile` sets.
|
|
39
|
+
*
|
|
40
|
+
* @throws AgentJamError if no agent with that name exists.
|
|
41
|
+
*/
|
|
42
|
+
update(name: string, profile: ProfileUpdate): Promise<StoredAgent>;
|
|
43
|
+
/**
|
|
44
|
+
* Connects an agent the relay stores and starts delivering its envelopes to `receive`, which
|
|
45
|
+
* resolves once the agent has handled each one. An accepted proposal is handled once its task
|
|
46
|
+
* ends, so keep delivering other envelopes in the meantime. `events` hears about sessions lost
|
|
47
|
+
* after connecting, and `options` names the instance the session runs as.
|
|
48
|
+
*
|
|
49
|
+
* @throws AgentJamError if no agent with that name exists, or another connection holds the instance.
|
|
50
|
+
*/
|
|
51
|
+
connect(name: string, receive: (envelope: Envelope) => Promise<void>, events?: SessionEvents, options?: SessionOptions): Promise<Connection>;
|
|
52
|
+
}
|
|
53
|
+
/** A task or schedule's use of the credential its skill's secret connection to `provider` holds. */
|
|
54
|
+
export type SecretGrant = ConnectionHolder & {
|
|
55
|
+
/** The provider of the secret connection. */
|
|
56
|
+
provider: string;
|
|
57
|
+
};
|
|
58
|
+
/** How a connection reaches the credentials the platform holds for secret connections, whose keys never reach the agent. */
|
|
59
|
+
export interface CredentialChannel {
|
|
60
|
+
/** Holds the principal's live credential for `grant`, or returns the link to the form where their human enters one. */
|
|
61
|
+
authorize(grant: SecretGrant): Promise<string | undefined>;
|
|
62
|
+
/** Stops `grant` from using the credential once its task or schedule ended. */
|
|
63
|
+
release(grant: SecretGrant): Promise<void>;
|
|
64
|
+
/** Returns the credential's non-secret fields, and throws `ConnectionRevokedError` once it's gone. */
|
|
65
|
+
config(grant: SecretGrant): Promise<Record<string, string>>;
|
|
66
|
+
/** Sends a request to the credential's provider through the platform, which adds the credential. */
|
|
67
|
+
fetch(grant: SecretGrant, ...request: Parameters<ConnectionFetch>): Promise<Response>;
|
|
68
|
+
/** Keeps the grants of OAuth connections without a store, unless the relay holds none. */
|
|
69
|
+
readonly oauth?: OAuthChannel;
|
|
70
|
+
}
|
|
71
|
+
/** One agent's live session with a relay. */
|
|
72
|
+
export interface Connection {
|
|
73
|
+
/** The name the relay connected the agent under. */
|
|
74
|
+
readonly name: string;
|
|
75
|
+
/** The agent's profile as the relay stores it, which can change while it's connected. */
|
|
76
|
+
readonly card: AgentCard;
|
|
77
|
+
/** The link where the human claims this agent while it's an unclaimed guest, refreshed on every connect. */
|
|
78
|
+
readonly claimUrl?: string | undefined;
|
|
79
|
+
/** The link where the human sets up payouts while this agent's paid skills wait for them, refreshed on every connect. */
|
|
80
|
+
readonly payoutsUrl?: string | undefined;
|
|
81
|
+
/**
|
|
82
|
+
* Sends an envelope, which the relay stamps with this agent's name.
|
|
83
|
+
*
|
|
84
|
+
* @throws AgentNotFoundError if the recipient isn't connected.
|
|
85
|
+
*/
|
|
86
|
+
send(envelope: EnvelopeDraft): Promise<void>;
|
|
87
|
+
/** Lists connected agents matching the query. */
|
|
88
|
+
find(query: AgentQuery): Promise<AgentCard[]>;
|
|
89
|
+
/**
|
|
90
|
+
* Rates the executor of a task this agent requested, once the task completed with an artifact. Connections without reviews leave it out.
|
|
91
|
+
*
|
|
92
|
+
* @throws AgentJamError if the task isn't eligible or this agent already reviewed it.
|
|
93
|
+
*/
|
|
94
|
+
rate?(review: ReviewDraft): Promise<Review>;
|
|
95
|
+
/**
|
|
96
|
+
* Disputes a task this agent requested and its human paid for, while the charge is still held. Connections without disputes leave it out.
|
|
97
|
+
*
|
|
98
|
+
* @throws AgentJamError if the task isn't this human's to dispute, its hold ended, or it's already disputed.
|
|
99
|
+
*/
|
|
100
|
+
dispute?(taskId: string, reason: string): Promise<Dispute>;
|
|
101
|
+
/** Lists the reviews of the named agent, newest first. Connections without reviews leave it out. */
|
|
102
|
+
reviews?(name: string, query: ReviewQuery): Promise<ReviewPage>;
|
|
103
|
+
/** Unregisters the agent and stops delivery. */
|
|
104
|
+
close(): Promise<void>;
|
|
105
|
+
/** Buys `amountCents` of credits and resolves with the account. Connections that can't pay leave it out. */
|
|
106
|
+
topUp?(amountCents: number): Promise<CreditAccount>;
|
|
107
|
+
/** Funds auto-reload from a recurring token and resolves with the account. Connections that can't pay leave it out. */
|
|
108
|
+
setAutoReload?(settings: AutoReloadSettings): Promise<CreditAccount>;
|
|
109
|
+
/** Lists the active trigger schedules this agent executes. Connections that leave it out only start triggers as schedules are accepted. */
|
|
110
|
+
triggers?(): Promise<TriggerSchedule[]>;
|
|
111
|
+
/** Lists the tasks this agent delegated that match the query, newest first. Connections that don't keep tasks leave it out. */
|
|
112
|
+
tasks?(query: TaskQuery): Promise<TaskPage>;
|
|
113
|
+
/**
|
|
114
|
+
* Recaps a task this agent executed, such as the one a follow-up's recap names. Connections that don't keep tasks leave it out.
|
|
115
|
+
*
|
|
116
|
+
* @throws AgentJamError if no such task exists or this agent didn't execute it.
|
|
117
|
+
*/
|
|
118
|
+
recall?(task: TaskRef): Promise<TaskRecapRef>;
|
|
119
|
+
/**
|
|
120
|
+
* Lists the ended tasks this agent ran before `anchor` that it may recall, newest first: earlier runs of a run's
|
|
121
|
+
* schedule, or earlier one-offs of a one-off's skill for the same human. Connections that don't keep tasks leave it out.
|
|
122
|
+
*
|
|
123
|
+
* @throws AgentJamError if this agent didn't execute `anchor`, or `query` is invalid.
|
|
124
|
+
*/
|
|
125
|
+
history?(anchor: TaskRef, query: HistoryQuery): Promise<HistoryPage>;
|
|
126
|
+
/** Uploads a file a proposal can attach and resolves with its upload id. Connections that can't store files leave it out. */
|
|
127
|
+
upload?(file: File, signal?: AbortSignal): Promise<string>;
|
|
128
|
+
/** Reaches the credentials of secret connections. Connections without a credential store leave it out. */
|
|
129
|
+
readonly credentials?: CredentialChannel;
|
|
130
|
+
}
|
|
131
|
+
/** A connection to a relay that keeps reviews and tasks and stores files. */
|
|
132
|
+
export type NetworkConnection = Connection & Required<Pick<Connection, "rate" | "dispute" | "reviews" | "tasks" | "recall" | "history" | "upload" | "credentials">>;
|
|
133
|
+
//# sourceMappingURL=relay.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,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CAC1C;AAED,6EAA6E;AAC7E,MAAM,MAAM,iBAAiB,GAAG,UAAU,GACxC,QAAQ,CACN,IAAI,CACF,UAAU,EACR,MAAM,GACN,SAAS,GACT,SAAS,GACT,OAAO,GACP,QAAQ,GACR,SAAS,GACT,QAAQ,GACR,aAAa,CAChB,CACF,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"relay.js","sourceRoot":"","sources":["../../src/relay/relay.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Envelope } from "../protocol.js";
|
|
2
|
+
import type { ProfileUpdate, StoredAgent } from "../types.js";
|
|
3
|
+
import type { Endpoints } from "./endpoints.js";
|
|
4
|
+
import type { Payments } from "./payments.js";
|
|
5
|
+
import type { NetworkConnection, Relay, SessionEvents, SessionOptions } from "./relay.js";
|
|
6
|
+
/** Options for `AgentJamRelay`. Every option falls back to an environment variable. */
|
|
7
|
+
export type AgentJamRelayOptions = Partial<Endpoints> & {
|
|
8
|
+
/** Your account's API key, or a guest's. Defaults to `AGENTJAM_API_KEY`. */
|
|
9
|
+
apiKey?: string | undefined;
|
|
10
|
+
/** Buys credits for the owner over MPP through `topUp()` and `setAutoReload()`. */
|
|
11
|
+
payments?: Payments | undefined;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* The AgentJam network, which `create()` and `connect()` use by default. It retries while the relay is
|
|
15
|
+
* unavailable, and resumes the agent's session after a dropped connection, so envelopes sent in the
|
|
16
|
+
* meantime arrive. With an account's API key, it creates, updates and connects that account's agents.
|
|
17
|
+
* Without a key, creating an agent makes a guest and saves its key on this machine, which connecting
|
|
18
|
+
* under that name then uses. A guest can only delegate free tasks until its human claims it.
|
|
19
|
+
* URLs default to the hosted network.
|
|
20
|
+
*/
|
|
21
|
+
export declare class AgentJamRelay implements Relay {
|
|
22
|
+
/** The URLs this relay connects to. */
|
|
23
|
+
readonly endpoints: Endpoints;
|
|
24
|
+
private readonly apiKey;
|
|
25
|
+
private readonly payments;
|
|
26
|
+
private readonly timing;
|
|
27
|
+
/**
|
|
28
|
+
* Creates a relay without connecting to it yet.
|
|
29
|
+
*
|
|
30
|
+
* @param options The API key and URLs, which default to `AGENTJAM_API_KEY`, `AGENTJAM_RELAY_URL` and `AGENTJAM_API_URL`, and how to pay for priced skills.
|
|
31
|
+
*/
|
|
32
|
+
constructor(options?: AgentJamRelayOptions);
|
|
33
|
+
create(name: string, profile: ProfileUpdate): Promise<StoredAgent>;
|
|
34
|
+
update(name: string, profile: ProfileUpdate): Promise<StoredAgent>;
|
|
35
|
+
connect(name: string, receive: (envelope: Envelope) => Promise<void>, events?: SessionEvents, { instanceId }?: SessionOptions): Promise<NetworkConnection>;
|
|
36
|
+
private account;
|
|
37
|
+
private guestKey;
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=remote.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"remote.d.ts","sourceRoot":"","sources":["../../src/relay/remote.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,QAAQ,EAA0B,MAAM,gBAAgB,CAAC;AACvE,OAAO,KAAK,EAIV,aAAa,EAGb,WAAW,EAGZ,MAAM,aAAa,CAAC;AAErB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAwBhD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAG9C,OAAO,KAAK,EAEV,iBAAiB,EACjB,KAAK,EACL,aAAa,EACb,cAAc,EACf,MAAM,YAAY,CAAC;AAiGpB,uFAAuF;AACvF,MAAM,MAAM,oBAAoB,GAAG,OAAO,CAAC,SAAS,CAAC,GAAG;IACtD,4EAA4E;IAC5E,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,mFAAmF;IACnF,QAAQ,CAAC,EAAE,QAAQ,GAAG,SAAS,CAAC;CAGjC,CAAC;AAEF;;;;;;;GAOG;AACH,qBAAa,aAAc,YAAW,KAAK;IACzC,uCAAuC;IACvC,SAAgB,SAAS,EAAE,SAAS,CAAC;IACrC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAqB;IAC5C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAuB;IAChD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAEhC;;;;OAIG;IACH,YAAY,OAAO,GAAE,oBAAyB,EAS7C;IAEY,MAAM,CACjB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,aAAa,GACrB,OAAO,CAAC,WAAW,CAAC,CAkBtB;IAEY,MAAM,CACjB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,aAAa,GACrB,OAAO,CAAC,WAAW,CAAC,CAStB;IAEY,OAAO,CAClB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,CAAC,QAAQ,EAAE,QAAQ,KAAK,OAAO,CAAC,IAAI,CAAC,EAC9C,MAAM,GAAE,aAAkB,EAC1B,EAAE,UAAU,EAAE,GAAE,cAAmB,GAClC,OAAO,CAAC,iBAAiB,CAAC,CAwB5B;IAED,OAAO,CAAC,OAAO;YAID,QAAQ;CAMvB"}
|
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
import { WebSocket } from "ws";
|
|
2
|
+
import { AgentExistsError, AgentJamError, DispatchFailedError, InstanceTakenError, TriggerFailedError, } from "../errors.js";
|
|
3
|
+
import { RemoteCredentials } from "./credentials.js";
|
|
4
|
+
import { agentNameHeader, resolveEndpoints } from "./endpoints.js";
|
|
5
|
+
import { closeError, failureError, fromWire, KeyRejectedError, maxFrameBytes, pastTaskFromWire, refusalError, scheduleFromWire, taskFromWire, TransientError, } from "./frames.js";
|
|
6
|
+
import { createGuest } from "./guests.js";
|
|
7
|
+
import { guestStore } from "./guestStore.js";
|
|
8
|
+
import { PayingConnection } from "./payments.js";
|
|
9
|
+
import { createAgent, updateAgent } from "./profiles.js";
|
|
10
|
+
import { uploadFile } from "./uploads.js";
|
|
11
|
+
const encode = (frame) => JSON.stringify(frame);
|
|
12
|
+
const defaultTiming = {
|
|
13
|
+
retryDelay: 500,
|
|
14
|
+
maxRetryDelay: 30_000,
|
|
15
|
+
heartbeatTimeout: 45_000,
|
|
16
|
+
byeTimeout: 5_000,
|
|
17
|
+
connectTimeout: 30_000,
|
|
18
|
+
maxFireAge: 60 * 60_000,
|
|
19
|
+
};
|
|
20
|
+
const STALE_EVENT = "The relay stayed unreachable too long, so the event was dropped rather than sent late";
|
|
21
|
+
const staleEventOf = ({ frame }) => {
|
|
22
|
+
if (frame.type !== "send")
|
|
23
|
+
return;
|
|
24
|
+
const { envelope } = frame;
|
|
25
|
+
if (envelope.type === "trigger.dispatch") {
|
|
26
|
+
return new DispatchFailedError(envelope.eventId, STALE_EVENT);
|
|
27
|
+
}
|
|
28
|
+
if (envelope.type !== "trigger.fire")
|
|
29
|
+
return;
|
|
30
|
+
const { to, scheduleId, eventId } = envelope;
|
|
31
|
+
return new TriggerFailedError(to, scheduleId, eventId, STALE_EVENT);
|
|
32
|
+
};
|
|
33
|
+
const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
34
|
+
const blankCard = (name) => ({
|
|
35
|
+
name,
|
|
36
|
+
description: "",
|
|
37
|
+
skills: [],
|
|
38
|
+
});
|
|
39
|
+
const isBlank = ({ description, skills, visibility }) => !description && !skills?.length && visibility === undefined;
|
|
40
|
+
const guestProfile = (name) => new AgentJamError(`Guests can't have a profile. Pass your account's apiKey or set AGENTJAM_API_KEY to give "${name}" a description, skills or visibility, or leave them out for a guest`);
|
|
41
|
+
const unsavedGuest = (name) => new AgentJamError(`No guest named "${name}" is saved on this machine. Create it with create({ name: "${name}" }), or pass your account's apiKey or set AGENTJAM_API_KEY to connect an agent on your account`);
|
|
42
|
+
const forgottenGuest = (name) => new AgentJamError(`The relay no longer knows the guest "${name}" this machine saved, so it was forgotten. Create it again with create({ name: "${name}" })`);
|
|
43
|
+
const bodyOf = async (response) => {
|
|
44
|
+
let body = "";
|
|
45
|
+
for await (const chunk of response)
|
|
46
|
+
body += chunk.toString();
|
|
47
|
+
return body;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* The AgentJam network, which `create()` and `connect()` use by default. It retries while the relay is
|
|
51
|
+
* unavailable, and resumes the agent's session after a dropped connection, so envelopes sent in the
|
|
52
|
+
* meantime arrive. With an account's API key, it creates, updates and connects that account's agents.
|
|
53
|
+
* Without a key, creating an agent makes a guest and saves its key on this machine, which connecting
|
|
54
|
+
* under that name then uses. A guest can only delegate free tasks until its human claims it.
|
|
55
|
+
* URLs default to the hosted network.
|
|
56
|
+
*/
|
|
57
|
+
export class AgentJamRelay {
|
|
58
|
+
/** The URLs this relay connects to. */
|
|
59
|
+
endpoints;
|
|
60
|
+
apiKey;
|
|
61
|
+
payments;
|
|
62
|
+
timing;
|
|
63
|
+
/**
|
|
64
|
+
* Creates a relay without connecting to it yet.
|
|
65
|
+
*
|
|
66
|
+
* @param options The API key and URLs, which default to `AGENTJAM_API_KEY`, `AGENTJAM_RELAY_URL` and `AGENTJAM_API_URL`, and how to pay for priced skills.
|
|
67
|
+
*/
|
|
68
|
+
constructor(options = {}) {
|
|
69
|
+
// WARNING: Destructuring in the signature leaks the internal `timing` option into the published types.
|
|
70
|
+
const { apiKey, payments, timing, ...endpoints } = options;
|
|
71
|
+
this.endpoints = { ...resolveEndpoints(), ...endpoints };
|
|
72
|
+
this.apiKey = apiKey || process.env.AGENTJAM_API_KEY || undefined;
|
|
73
|
+
this.payments = payments;
|
|
74
|
+
this.timing = { ...defaultTiming, ...timing };
|
|
75
|
+
}
|
|
76
|
+
async create(name, profile) {
|
|
77
|
+
if (this.apiKey) {
|
|
78
|
+
return createAgent(this.account(this.apiKey), name, profile);
|
|
79
|
+
}
|
|
80
|
+
if (!isBlank(profile))
|
|
81
|
+
throw guestProfile(name);
|
|
82
|
+
const { apiUrl } = this.endpoints;
|
|
83
|
+
if (await guestStore.load(apiUrl, name)) {
|
|
84
|
+
throw new AgentExistsError(`This machine already saved the guest "${name}". Connect it with connect({ name: "${name}" })`);
|
|
85
|
+
}
|
|
86
|
+
const { name: address, key, claimUrl } = await createGuest(apiUrl, name);
|
|
87
|
+
await guestStore.save(apiUrl, name, { key, claimUrl });
|
|
88
|
+
return { card: blankCard(address), claimUrl };
|
|
89
|
+
}
|
|
90
|
+
async update(name, profile) {
|
|
91
|
+
if (this.apiKey) {
|
|
92
|
+
return updateAgent(this.account(this.apiKey), name, profile);
|
|
93
|
+
}
|
|
94
|
+
if (!isBlank(profile))
|
|
95
|
+
throw guestProfile(name);
|
|
96
|
+
await this.guestKey(name);
|
|
97
|
+
return { card: blankCard(name) };
|
|
98
|
+
}
|
|
99
|
+
async connect(name, receive, events = {}, { instanceId } = {}) {
|
|
100
|
+
const apiKey = this.apiKey ?? (await this.guestKey(name));
|
|
101
|
+
const connection = await RemoteConnection.open({
|
|
102
|
+
url: this.endpoints.relayUrl,
|
|
103
|
+
apiUrl: this.endpoints.apiUrl,
|
|
104
|
+
proxyUrl: this.endpoints.proxyUrl,
|
|
105
|
+
name,
|
|
106
|
+
apiKey,
|
|
107
|
+
receive,
|
|
108
|
+
events,
|
|
109
|
+
instanceId,
|
|
110
|
+
timing: this.timing,
|
|
111
|
+
}).catch(async (error) => {
|
|
112
|
+
if (this.apiKey || !(error instanceof KeyRejectedError))
|
|
113
|
+
throw error;
|
|
114
|
+
await guestStore.forget(this.endpoints.apiUrl, name, apiKey);
|
|
115
|
+
throw forgottenGuest(name);
|
|
116
|
+
});
|
|
117
|
+
if (!this.payments)
|
|
118
|
+
return connection;
|
|
119
|
+
return new PayingConnection(connection, {
|
|
120
|
+
...this.account(apiKey),
|
|
121
|
+
payments: this.payments,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
account(apiKey) {
|
|
125
|
+
return { apiUrl: this.endpoints.apiUrl, apiKey };
|
|
126
|
+
}
|
|
127
|
+
async guestKey(name) {
|
|
128
|
+
const saved = await guestStore.load(this.endpoints.apiUrl, name);
|
|
129
|
+
if (!saved)
|
|
130
|
+
throw unsavedGuest(name);
|
|
131
|
+
return saved.key;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
// Invariant: `socket` is set only from a welcome until that socket closes, so requests and acks follow the handshake.
|
|
135
|
+
class RemoteConnection {
|
|
136
|
+
settings;
|
|
137
|
+
profile;
|
|
138
|
+
socket;
|
|
139
|
+
session;
|
|
140
|
+
claim;
|
|
141
|
+
payouts;
|
|
142
|
+
closed;
|
|
143
|
+
heartbeat;
|
|
144
|
+
retry;
|
|
145
|
+
references = 0;
|
|
146
|
+
pending = new Map();
|
|
147
|
+
handling = new Set();
|
|
148
|
+
unacked = new Set();
|
|
149
|
+
credentials;
|
|
150
|
+
constructor(settings) {
|
|
151
|
+
this.settings = settings;
|
|
152
|
+
this.credentials = new RemoteCredentials(settings);
|
|
153
|
+
}
|
|
154
|
+
static async open(settings) {
|
|
155
|
+
const connection = new RemoteConnection(settings);
|
|
156
|
+
await connection.start();
|
|
157
|
+
return connection;
|
|
158
|
+
}
|
|
159
|
+
get name() {
|
|
160
|
+
return this.profile?.name ?? this.settings.name;
|
|
161
|
+
}
|
|
162
|
+
get card() {
|
|
163
|
+
if (!this.profile) {
|
|
164
|
+
throw new AgentJamError("The relay hasn't welcomed this agent yet");
|
|
165
|
+
}
|
|
166
|
+
return this.profile;
|
|
167
|
+
}
|
|
168
|
+
get claimUrl() {
|
|
169
|
+
return this.claim;
|
|
170
|
+
}
|
|
171
|
+
get payoutsUrl() {
|
|
172
|
+
return this.payouts;
|
|
173
|
+
}
|
|
174
|
+
async send(envelope) {
|
|
175
|
+
await this.request({ type: "send", ref: this.nextReference(), envelope });
|
|
176
|
+
}
|
|
177
|
+
async find(query) {
|
|
178
|
+
const { cards } = await this.request({
|
|
179
|
+
type: "find",
|
|
180
|
+
ref: this.nextReference(),
|
|
181
|
+
query,
|
|
182
|
+
});
|
|
183
|
+
return cards;
|
|
184
|
+
}
|
|
185
|
+
async rate(review) {
|
|
186
|
+
const reply = await this.request({
|
|
187
|
+
type: "rate",
|
|
188
|
+
ref: this.nextReference(),
|
|
189
|
+
review,
|
|
190
|
+
});
|
|
191
|
+
return fromWire(reply.review);
|
|
192
|
+
}
|
|
193
|
+
async dispute(taskId, reason) {
|
|
194
|
+
const reply = await this.request({
|
|
195
|
+
type: "dispute",
|
|
196
|
+
ref: this.nextReference(),
|
|
197
|
+
taskId,
|
|
198
|
+
reason,
|
|
199
|
+
});
|
|
200
|
+
return reply.dispute;
|
|
201
|
+
}
|
|
202
|
+
async reviews(name, query) {
|
|
203
|
+
const { reviews, next } = await this.request({
|
|
204
|
+
type: "reviews",
|
|
205
|
+
ref: this.nextReference(),
|
|
206
|
+
query: { ...query, name },
|
|
207
|
+
});
|
|
208
|
+
return {
|
|
209
|
+
reviews: reviews.map(fromWire),
|
|
210
|
+
...(next === undefined ? {} : { next }),
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
async triggers() {
|
|
214
|
+
const schedules = [];
|
|
215
|
+
let cursor;
|
|
216
|
+
do {
|
|
217
|
+
const page = await this.request({
|
|
218
|
+
type: "triggers",
|
|
219
|
+
ref: this.nextReference(),
|
|
220
|
+
...(cursor === undefined ? {} : { cursor }),
|
|
221
|
+
});
|
|
222
|
+
schedules.push(...page.schedules.map(scheduleFromWire));
|
|
223
|
+
cursor = page.next;
|
|
224
|
+
} while (cursor !== undefined);
|
|
225
|
+
return schedules;
|
|
226
|
+
}
|
|
227
|
+
async tasks(query) {
|
|
228
|
+
const { tasks, next } = await this.request({
|
|
229
|
+
type: "tasks",
|
|
230
|
+
ref: this.nextReference(),
|
|
231
|
+
query,
|
|
232
|
+
});
|
|
233
|
+
return {
|
|
234
|
+
tasks: tasks.map(taskFromWire),
|
|
235
|
+
...(next === undefined ? {} : { next }),
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
async recall(task) {
|
|
239
|
+
const recalled = await this.request({
|
|
240
|
+
type: "recall",
|
|
241
|
+
ref: this.nextReference(),
|
|
242
|
+
task,
|
|
243
|
+
});
|
|
244
|
+
return recalled.task;
|
|
245
|
+
}
|
|
246
|
+
async history(anchor, query) {
|
|
247
|
+
const { tasks, next } = await this.request({
|
|
248
|
+
type: "history",
|
|
249
|
+
ref: this.nextReference(),
|
|
250
|
+
anchor,
|
|
251
|
+
query,
|
|
252
|
+
});
|
|
253
|
+
return {
|
|
254
|
+
tasks: tasks.map(pastTaskFromWire),
|
|
255
|
+
...(next === undefined ? {} : { next }),
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
upload(file, signal) {
|
|
259
|
+
const { apiUrl, apiKey, name } = this.settings;
|
|
260
|
+
return uploadFile({ apiUrl, apiKey }, name, file, signal);
|
|
261
|
+
}
|
|
262
|
+
async close() {
|
|
263
|
+
if (this.closed)
|
|
264
|
+
return;
|
|
265
|
+
const socket = this.socket;
|
|
266
|
+
this.stop(new AgentJamError(`The connection for "${this.name}" is closed`));
|
|
267
|
+
if (!socket)
|
|
268
|
+
return;
|
|
269
|
+
const closed = new Promise((resolve) => socket.once("close", resolve));
|
|
270
|
+
const timer = setTimeout(() => socket.terminate(), this.settings.timing.byeTimeout);
|
|
271
|
+
socket.send(encode({ type: "bye" }));
|
|
272
|
+
await closed;
|
|
273
|
+
clearTimeout(timer);
|
|
274
|
+
}
|
|
275
|
+
async start() {
|
|
276
|
+
const deadline = Date.now() + this.settings.timing.connectTimeout;
|
|
277
|
+
let attempt = 0;
|
|
278
|
+
while (true) {
|
|
279
|
+
try {
|
|
280
|
+
return await this.dial();
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
const delay = this.delayAfter(error, attempt);
|
|
284
|
+
if (delay === undefined || Date.now() + delay > deadline)
|
|
285
|
+
throw error;
|
|
286
|
+
attempt += 1;
|
|
287
|
+
await sleep(delay);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
delayAfter(error, attempt) {
|
|
292
|
+
if (error instanceof InstanceTakenError) {
|
|
293
|
+
return error.retryAfterMs + this.backoff(0);
|
|
294
|
+
}
|
|
295
|
+
return error instanceof TransientError ? this.backoff(attempt) : undefined;
|
|
296
|
+
}
|
|
297
|
+
dial() {
|
|
298
|
+
const { url, name, apiKey, instanceId } = this.settings;
|
|
299
|
+
const socket = new WebSocket(url, {
|
|
300
|
+
headers: {
|
|
301
|
+
authorization: `Bearer ${apiKey}`,
|
|
302
|
+
[agentNameHeader]: encodeURIComponent(name),
|
|
303
|
+
},
|
|
304
|
+
});
|
|
305
|
+
const welcomed = Promise.withResolvers();
|
|
306
|
+
let opened = false;
|
|
307
|
+
let refusal;
|
|
308
|
+
const failure = (code, reason) => refusal ??
|
|
309
|
+
(opened
|
|
310
|
+
? closeError(code, name, reason, instanceId)
|
|
311
|
+
: new TransientError(`Could not reach the relay at ${url}`));
|
|
312
|
+
this.watch(socket);
|
|
313
|
+
// WARNING: every error is followed by a close, which decides whether to reconnect.
|
|
314
|
+
socket.on("error", () => { });
|
|
315
|
+
socket.on("unexpected-response", (_request, response) => {
|
|
316
|
+
void bodyOf(response)
|
|
317
|
+
.catch(() => "")
|
|
318
|
+
.then((body) => {
|
|
319
|
+
refusal = refusalError(response.statusCode ?? 0, name, body);
|
|
320
|
+
socket.terminate();
|
|
321
|
+
});
|
|
322
|
+
});
|
|
323
|
+
socket.on("open", () => {
|
|
324
|
+
opened = true;
|
|
325
|
+
const resume = this.session === undefined ? {} : { resume: this.session };
|
|
326
|
+
const instance = instanceId === undefined ? {} : { instanceId };
|
|
327
|
+
socket.send(encode({ type: "hello", ...resume, ...instance }));
|
|
328
|
+
});
|
|
329
|
+
socket.on("ping", () => this.watch(socket));
|
|
330
|
+
socket.on("message", (data) => {
|
|
331
|
+
const frame = JSON.parse(data.toString());
|
|
332
|
+
this.watch(socket);
|
|
333
|
+
this.receive(socket, frame);
|
|
334
|
+
if (frame.type === "welcome")
|
|
335
|
+
welcomed.resolve();
|
|
336
|
+
});
|
|
337
|
+
socket.once("close", (code, reason) => {
|
|
338
|
+
clearTimeout(this.heartbeat);
|
|
339
|
+
if (this.socket === socket)
|
|
340
|
+
return this.disconnect(code, String(reason));
|
|
341
|
+
welcomed.reject(failure(code, String(reason)));
|
|
342
|
+
});
|
|
343
|
+
return welcomed.promise;
|
|
344
|
+
}
|
|
345
|
+
receive(socket, frame) {
|
|
346
|
+
switch (frame.type) {
|
|
347
|
+
case "welcome":
|
|
348
|
+
return this.attach(socket, frame);
|
|
349
|
+
case "deliver":
|
|
350
|
+
return this.deliver(frame.delivery, frame.envelope);
|
|
351
|
+
case "sent":
|
|
352
|
+
case "found":
|
|
353
|
+
case "rated":
|
|
354
|
+
case "disputed":
|
|
355
|
+
case "reviewed":
|
|
356
|
+
case "listed":
|
|
357
|
+
case "summarized":
|
|
358
|
+
case "recalled":
|
|
359
|
+
case "chronicled":
|
|
360
|
+
return this.take(frame.ref)?.resolve(frame);
|
|
361
|
+
case "failed":
|
|
362
|
+
return this.fail(frame);
|
|
363
|
+
default: {
|
|
364
|
+
// WARNING: throwing here would crash the process, so frames added by newer relays are ignored.
|
|
365
|
+
const ignored = frame;
|
|
366
|
+
return ignored;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
attach(socket, { card, session, resumed, claimUrl, payoutsUrl, }) {
|
|
371
|
+
if (this.closed) {
|
|
372
|
+
socket.send(encode({ type: "bye" }));
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
const replaced = !resumed && this.session !== undefined;
|
|
376
|
+
this.profile = card;
|
|
377
|
+
this.socket = socket;
|
|
378
|
+
this.session = session;
|
|
379
|
+
this.claim = claimUrl;
|
|
380
|
+
this.payouts = payoutsUrl;
|
|
381
|
+
if (!resumed)
|
|
382
|
+
this.unacked.clear();
|
|
383
|
+
this.dropStaleEvents();
|
|
384
|
+
for (const { wire } of this.pending.values())
|
|
385
|
+
socket.send(wire);
|
|
386
|
+
if (replaced)
|
|
387
|
+
this.settings.events.onSessionReplaced?.();
|
|
388
|
+
}
|
|
389
|
+
dropStaleEvents() {
|
|
390
|
+
const cutoff = Date.now() - this.settings.timing.maxFireAge;
|
|
391
|
+
for (const [reference, request] of this.pending) {
|
|
392
|
+
const stale = request.queuedAt < cutoff && staleEventOf(request);
|
|
393
|
+
if (!stale)
|
|
394
|
+
continue;
|
|
395
|
+
this.pending.delete(reference);
|
|
396
|
+
request.reject(stale);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
disconnect(code, reason) {
|
|
400
|
+
this.socket = undefined;
|
|
401
|
+
const { name, instanceId } = this.settings;
|
|
402
|
+
const error = closeError(code, name, reason, instanceId);
|
|
403
|
+
if (error instanceof TransientError)
|
|
404
|
+
return this.reconnect();
|
|
405
|
+
this.lose(error);
|
|
406
|
+
}
|
|
407
|
+
reconnect(attempt = 0) {
|
|
408
|
+
this.retry = setTimeout(() => {
|
|
409
|
+
this.dial().catch((error) => {
|
|
410
|
+
if (this.closed)
|
|
411
|
+
return;
|
|
412
|
+
if (error instanceof TransientError)
|
|
413
|
+
return this.reconnect(attempt + 1);
|
|
414
|
+
this.lose(error);
|
|
415
|
+
});
|
|
416
|
+
}, this.backoff(attempt));
|
|
417
|
+
}
|
|
418
|
+
backoff(attempt) {
|
|
419
|
+
const { retryDelay, maxRetryDelay } = this.settings.timing;
|
|
420
|
+
const ceiling = Math.min(maxRetryDelay, retryDelay * 2 ** attempt);
|
|
421
|
+
return ceiling * (0.5 + Math.random() / 2);
|
|
422
|
+
}
|
|
423
|
+
lose(error) {
|
|
424
|
+
this.stop(error);
|
|
425
|
+
this.settings.events.onError?.(error);
|
|
426
|
+
}
|
|
427
|
+
stop(error) {
|
|
428
|
+
this.closed = error;
|
|
429
|
+
this.socket = undefined;
|
|
430
|
+
clearTimeout(this.heartbeat);
|
|
431
|
+
clearTimeout(this.retry);
|
|
432
|
+
for (const request of this.pending.values())
|
|
433
|
+
request.reject(error);
|
|
434
|
+
this.pending.clear();
|
|
435
|
+
}
|
|
436
|
+
deliver(delivery, envelope) {
|
|
437
|
+
if (this.handling.has(delivery))
|
|
438
|
+
return;
|
|
439
|
+
if (this.unacked.delete(delivery))
|
|
440
|
+
return this.acknowledge(delivery);
|
|
441
|
+
const handled = () => {
|
|
442
|
+
this.handling.delete(delivery);
|
|
443
|
+
this.acknowledge(delivery);
|
|
444
|
+
};
|
|
445
|
+
this.handling.add(delivery);
|
|
446
|
+
void this.settings.receive(envelope).then(handled, handled);
|
|
447
|
+
}
|
|
448
|
+
acknowledge(delivery) {
|
|
449
|
+
if (this.socket) {
|
|
450
|
+
this.socket.send(encode({ type: "ack", delivery }));
|
|
451
|
+
}
|
|
452
|
+
else {
|
|
453
|
+
this.unacked.add(delivery);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
request(frame) {
|
|
457
|
+
if (this.closed)
|
|
458
|
+
return Promise.reject(this.closed);
|
|
459
|
+
const wire = encode(frame);
|
|
460
|
+
if (Buffer.byteLength(wire) > maxFrameBytes) {
|
|
461
|
+
return Promise.reject(new AgentJamError(`The ${frame.type} frame is too large for the relay's ${maxFrameBytes} byte limit`));
|
|
462
|
+
}
|
|
463
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
464
|
+
this.pending.set(frame.ref, {
|
|
465
|
+
frame,
|
|
466
|
+
wire,
|
|
467
|
+
queuedAt: Date.now(),
|
|
468
|
+
resolve,
|
|
469
|
+
reject,
|
|
470
|
+
});
|
|
471
|
+
this.socket?.send(wire);
|
|
472
|
+
return promise;
|
|
473
|
+
}
|
|
474
|
+
fail(failure) {
|
|
475
|
+
const request = this.take(failure.ref);
|
|
476
|
+
request?.reject(failureError(failure, request.frame));
|
|
477
|
+
}
|
|
478
|
+
take(reference) {
|
|
479
|
+
const request = this.pending.get(reference);
|
|
480
|
+
this.pending.delete(reference);
|
|
481
|
+
return request;
|
|
482
|
+
}
|
|
483
|
+
watch(socket) {
|
|
484
|
+
clearTimeout(this.heartbeat);
|
|
485
|
+
this.heartbeat = setTimeout(() => socket.terminate(), this.settings.timing.heartbeatTimeout);
|
|
486
|
+
}
|
|
487
|
+
nextReference() {
|
|
488
|
+
this.references += 1;
|
|
489
|
+
return `${this.references}`;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
//# sourceMappingURL=remote.js.map
|