@withgateway/sdk 0.4.0 → 0.6.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.
Files changed (94) hide show
  1. package/dist/cli.js +1128 -783
  2. package/dist/cli.js.map +1 -1
  3. package/dist/cli.mjs +1130 -785
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/files/index.js +47 -18
  6. package/dist/files/index.js.map +1 -1
  7. package/dist/files/index.mjs +47 -18
  8. package/dist/files/index.mjs.map +1 -1
  9. package/dist/{index-mJhG3vZU.d.mts → index-Di9nNqOY.d.mts} +26 -3
  10. package/dist/{index-DUHmS74p.d.ts → index-LA-PMRJT.d.ts} +26 -3
  11. package/dist/index.d.mts +3 -3
  12. package/dist/index.d.ts +3 -3
  13. package/dist/index.js +179 -43
  14. package/dist/index.js.map +1 -1
  15. package/dist/index.mjs +176 -43
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/replay/index.d.mts +1 -1
  18. package/dist/replay/index.d.ts +1 -1
  19. package/dist/replay/index.js.map +1 -1
  20. package/dist/replay/index.mjs.map +1 -1
  21. package/dist/traces/index.js +47 -18
  22. package/dist/traces/index.js.map +1 -1
  23. package/dist/traces/index.mjs +47 -18
  24. package/dist/traces/index.mjs.map +1 -1
  25. package/dist/tracing/index.d.mts +1 -1
  26. package/dist/tracing/index.d.ts +1 -1
  27. package/dist/tracing/index.js +1 -1
  28. package/dist/tracing/index.js.map +1 -1
  29. package/dist/tracing/index.mjs +1 -1
  30. package/dist/tracing/index.mjs.map +1 -1
  31. package/dist/worlds/index.d.mts +184 -85
  32. package/dist/worlds/index.d.ts +184 -85
  33. package/dist/worlds/index.js +176 -43
  34. package/dist/worlds/index.js.map +1 -1
  35. package/dist/worlds/index.mjs +176 -43
  36. package/dist/worlds/index.mjs.map +1 -1
  37. package/package.json +1 -1
  38. package/runtime/gatewaysdk/environment/_bundle.py +4 -6
  39. package/runtime/gatewaysdk/environment/_world.py +24 -1
  40. package/runtime/gatewaysdk/environment/runtime.py +45 -2
  41. package/runtime/gatewaysdk/environment/schema/api.py +24 -3
  42. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +1 -0
  43. package/runtime/gatewaysdk/environment/schema/call_capture.py +13 -1
  44. package/runtime/gatewaysdk/environment/schema/call_log.py +46 -0
  45. package/runtime/gatewaysdk/environment/schema/call_redaction.py +6 -0
  46. package/runtime/gatewaysdk/environment/schema/compiler.py +4 -1
  47. package/runtime/gatewaysdk/environment/schema/conform.py +32 -8
  48. package/runtime/gatewaysdk/environment/schema/connector.py +5 -0
  49. package/runtime/gatewaysdk/environment/schema/connectors/custom/handlers.py +2 -1
  50. package/runtime/gatewaysdk/environment/schema/connectors/github/api/handlers.py +217 -58
  51. package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +9 -19
  52. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_webhooks.json +10 -2
  53. package/runtime/gatewaysdk/environment/schema/connectors/github/tests/webhooks.json +47 -0
  54. package/runtime/gatewaysdk/environment/schema/connectors/github/world.json +21 -0
  55. package/runtime/gatewaysdk/environment/schema/connectors/jamf/api/handlers.py +185 -18
  56. package/runtime/gatewaysdk/environment/schema/connectors/jamf/connector.toml +29 -14
  57. package/runtime/gatewaysdk/environment/schema/connectors/jamf/provenance.json +43 -12
  58. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_webhooks.json +2 -2
  59. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scope.toml +4 -17
  60. package/runtime/gatewaysdk/environment/schema/connectors/jamf/tests/webhooks.json +107 -0
  61. package/runtime/gatewaysdk/environment/schema/connectors/jamf/vendor-openapi.json +1 -1
  62. package/runtime/gatewaysdk/environment/schema/connectors/linear/api/handlers.py +85 -1
  63. package/runtime/gatewaysdk/environment/schema/connectors/linear/connector.toml +19 -31
  64. package/runtime/gatewaysdk/environment/schema/connectors/linear/provenance.json +18 -8
  65. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/webhooks.json +19 -3
  66. package/runtime/gatewaysdk/environment/schema/connectors/linear/tests/test_webhooks.py +71 -0
  67. package/runtime/gatewaysdk/environment/schema/database/guard.py +2 -1
  68. package/runtime/gatewaysdk/environment/schema/handler_errors.py +27 -1
  69. package/runtime/gatewaysdk/environment/schema/journal.py +4 -3
  70. package/runtime/gatewaysdk/environment/schema/local.py +1 -0
  71. package/runtime/gatewaysdk/environment/schema/openapi_schemas.py +20 -5
  72. package/runtime/gatewaysdk/environment/schema/platform.py +16 -219
  73. package/runtime/gatewaysdk/environment/schema/runtime.py +7 -0
  74. package/runtime/gatewaysdk/environment/schema/scaffold.py +2 -1
  75. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  76. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +19 -22
  77. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +7 -9
  78. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +3 -3
  79. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +14 -11
  80. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +36 -5
  81. package/runtime/gatewaysdk/environment/schema/snapshot.py +2 -2
  82. package/runtime/gatewaysdk/environment/schema/tools_world.py +19 -0
  83. package/runtime/gatewaysdk/environment/schema/verbs.py +6 -0
  84. package/runtime/gatewaysdk/environment/schema/webhooks.py +687 -0
  85. package/runtime/gatewaysdk/environment/schema/world_host.py +20 -3
  86. package/runtime/gatewaysdk/environment/schema/world_tests.py +74 -0
  87. package/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  88. package/skills/connector-schema-authoring/SKILL.md +19 -22
  89. package/skills/connector-schema-authoring/connector-worlds.md +153 -11
  90. package/skills/connector-schema-authoring/world-schema.md +7 -6
  91. package/skills/world-data-ingestion/SKILL.md +7 -9
  92. package/skills/worlds-getting-started/SKILL.md +3 -3
  93. package/skills/worlds-getting-started/references/cli-mcp-map.md +14 -11
  94. package/skills/worlds-getting-started/references/gotchas.md +36 -5
@@ -4,11 +4,22 @@
4
4
  url, priorityLabel, branchName, timestamps); `*Archive` / `*Unarchive` stamp or clear
5
5
  `archivedAt`; `organization` answers the viewer's workspace. Everything persists through the
6
6
  contract, so a body the schema refuses is the vendor's 400.
7
+
8
+ Issue and comment writes send Linear's data change webhook (`action`, `type`, `data`, `url`,
9
+ `updatedFrom` on update) to each subscription that wants the resource type and holds the team.
7
10
  """
8
11
 
9
12
  import re
10
13
 
11
14
  PRIORITY_LABELS = {0: "No priority", 1: "Urgent", 2: "High", 3: "Medium", 4: "Low"}
15
+ WEBHOOK_DEFAULTS = {
16
+ "allPublicTeams": False,
17
+ "archivedAt": None,
18
+ "creatorId": None,
19
+ "enabled": True,
20
+ "label": None,
21
+ "teamId": None,
22
+ }
12
23
 
13
24
 
14
25
  def _nullable(prop):
@@ -87,6 +98,7 @@ def issue_create(ctx, args, query, body):
87
98
  created = ctx.insert("linear_issues", _complete(ctx, "linear_issues", row))
88
99
  for label_id in label_ids:
89
100
  ctx.insert("linear_issue_labels", {"issueId": created["id"], "labelId": label_id})
101
+ _notify(ctx, "create", "linear_issues", created)
90
102
  return 200, created
91
103
 
92
104
 
@@ -108,7 +120,9 @@ def comment_create(ctx, args, query, body):
108
120
  "createdAt": now,
109
121
  "updatedAt": now,
110
122
  }
111
- return 200, ctx.insert("linear_comments", _complete(ctx, "linear_comments", row))
123
+ created = ctx.insert("linear_comments", _complete(ctx, "linear_comments", row))
124
+ _notify(ctx, "create", "linear_comments", created)
125
+ return 200, created
112
126
 
113
127
 
114
128
  def _one(ctx, args):
@@ -117,6 +131,76 @@ def _one(ctx, args):
117
131
  return entity, row
118
132
 
119
133
 
134
+ def updated(ctx, args, query, body):
135
+ entity, row = _one(ctx, args)
136
+ if row is None:
137
+ return ctx.not_found()
138
+ patch = {"updatedAt": ctx.now(), **(body if isinstance(body, dict) else {})}
139
+ written = ctx.update(entity, {"id": row["id"]}, patch)
140
+ _notify(ctx, "update", entity, written, _previous(row, written))
141
+ return 200, written
142
+
143
+
144
+ def removed(ctx, args, query, body):
145
+ entity, row = _one(ctx, args)
146
+ if row is None:
147
+ return ctx.not_found()
148
+ ctx.delete(entity, {"id": row["id"]})
149
+ _notify(ctx, "remove", entity, row)
150
+ return 200, None
151
+
152
+
153
+ def webhook_create(ctx, args, query, body):
154
+ body = dict(body) if isinstance(body, dict) else {}
155
+ if not body.get("url"):
156
+ return ctx.invalid("url is required")
157
+ now = ctx.now()
158
+ row = {
159
+ **WEBHOOK_DEFAULTS,
160
+ **body,
161
+ "id": body.get("id") or ctx.uuid(),
162
+ "secret": body.get("secret") or ctx.uuid().replace("-", "") + ctx.uuid().replace("-", ""),
163
+ "createdAt": now,
164
+ "updatedAt": now,
165
+ }
166
+ return 200, ctx.insert("linear_webhooks", row)
167
+
168
+
169
+ def _previous(before, after):
170
+ return {name: before.get(name) for name, value in after.items() if before.get(name) != value}
171
+
172
+
173
+ def _issue_team(ctx, row):
174
+ return row.get("teamId")
175
+
176
+
177
+ def _comment_team(ctx, row):
178
+ issue = ctx.get("linear_issues", {"id": row["issueId"]}) if row.get("issueId") else None
179
+ return issue["teamId"] if issue else None
180
+
181
+
182
+ RESOURCES = {"linear_issues": ("Issue", _issue_team), "linear_comments": ("Comment", _comment_team)}
183
+
184
+
185
+ def _notify(ctx, action, entity, row, previous=None):
186
+ resource, team_of = RESOURCES[entity]
187
+ organizations = ctx.rows("linear_organizations")
188
+ payload = {
189
+ "action": action,
190
+ "type": resource,
191
+ "actor": None,
192
+ "createdAt": ctx.now(),
193
+ "data": row,
194
+ "url": row.get("url"),
195
+ "organizationId": organizations[0]["id"] if organizations else None,
196
+ "webhookTimestamp": int(ctx.clock() * 1000),
197
+ }
198
+ if previous is not None:
199
+ payload["updatedFrom"] = previous
200
+ team = team_of(ctx, row)
201
+ ctx.deliver(resource, payload, scope={"teamId": team} if team else None)
202
+
203
+
120
204
  def archive(ctx, args, query, body):
121
205
  entity, row = _one(ctx, args)
122
206
  if row is None:
@@ -1,25 +1,13 @@
1
- # Linear, served REST-shaped from the schema world.
2
- #
3
- # Linear's API is one GraphQL endpoint (POST https://api.linear.app/graphql). This world
4
- # serves the documented root queries and mutations of the pinned SDL as HTTP routes, one
5
- # per root field, named after that field in snake_case: `issues` -> GET /issues, `issue(id)` -> GET
6
- # /issues/{id}, `issueCreate` -> POST /issues, `issueUpdate` -> PATCH /issues/{id},
7
- # `issueDelete` -> DELETE /issues/{id}, `issueArchive` -> POST /issues/{id}/archive. A by-id
8
- # query whose name a mutation also uses (`projectUpdate`, `initiativeUpdate`) is `<name>_get`.
9
- # The paths are this world's, not the vendor's; the entities, fields, argument names,
10
- # auth header, page size and error body follow the vendor documents in provenance.json.
11
1
 
12
2
  [connector]
13
3
  slug = "linear"
14
4
  base_url = "https://api.linear.app"
15
5
 
16
- # linear.app/developers/graphql: personal API keys go in `Authorization: <API_KEY>`.
17
6
  [auth]
18
7
  scheme = "header"
19
8
  name = "Authorization"
20
9
  secret_env = "LINEAR_API_KEY"
21
10
 
22
- # linear.app/developers/rate-limiting: 2,500 requests per hour per API key.
23
11
  [capture]
24
12
  requests_per_minute = 40
25
13
  timeout_seconds = 30
@@ -31,7 +19,6 @@ cursor_field = "endCursor"
31
19
  hash = ["email", "name", "displayName", "initials", "description", "body", "bodyData", "avatarUrl", "domains", "externalIds", "phone", "url", "gitBranchFormat"]
32
20
  drop = ["secret", "templateData"]
33
21
 
34
- # Connections answer `{nodes, endCursor}` paged by `first`/`after` (default 50 records).
35
22
  [api]
36
23
  envelope = "nodes"
37
24
  hits_key = ""
@@ -49,10 +36,15 @@ invalid_status = 400
49
36
  invalid = '{"errors": [{"message": "Argument Validation Error"}]}'
50
37
  handlers = "api/handlers.py"
51
38
 
52
- # The browsable UI over these routes: `gateway worlds schema compile` generates
53
- # ui/static (index.html, app.js, contract.json) from the contract; a session
54
- # opened with `--surface ui` serves it and `--surface browser` drives it. Set
55
- # `generated = false` to hand-write ui/static instead.
39
+ [webhooks]
40
+ subscriptions = "linear_webhooks"
41
+ url = "url"
42
+ events = "resourceTypes"
43
+ secret = "secret"
44
+ enabled = "enabled"
45
+ scope = { teamId = "teamId" }
46
+ signing = "linear"
47
+
56
48
  [ui]
57
49
  static = "ui/static"
58
50
  entry = "/"
@@ -699,9 +691,8 @@ method = "PATCH"
699
691
  path = "/issues/{id}"
700
692
  entity = "linear_issues"
701
693
  [operations.api]
702
- action = "update"
703
- status = 200
704
- single = true
694
+ action = "handler"
695
+ handler = "updated"
705
696
  filter = { id = "id" }
706
697
 
707
698
  [[operations]]
@@ -710,8 +701,8 @@ method = "DELETE"
710
701
  path = "/issues/{id}"
711
702
  entity = "linear_issues"
712
703
  [operations.api]
713
- action = "delete"
714
- status = 200
704
+ action = "handler"
705
+ handler = "removed"
715
706
  filter = { id = "id" }
716
707
 
717
708
  [[operations]]
@@ -870,9 +861,8 @@ method = "PATCH"
870
861
  path = "/comments/{id}"
871
862
  entity = "linear_comments"
872
863
  [operations.api]
873
- action = "update"
874
- status = 200
875
- single = true
864
+ action = "handler"
865
+ handler = "updated"
876
866
  filter = { id = "id" }
877
867
 
878
868
  [[operations]]
@@ -881,8 +871,8 @@ method = "DELETE"
881
871
  path = "/comments/{id}"
882
872
  entity = "linear_comments"
883
873
  [operations.api]
884
- action = "delete"
885
- status = 200
874
+ action = "handler"
875
+ handler = "removed"
886
876
  filter = { id = "id" }
887
877
 
888
878
  [[operations]]
@@ -1476,10 +1466,8 @@ method = "POST"
1476
1466
  path = "/webhooks"
1477
1467
  entity = "linear_webhooks"
1478
1468
  [operations.api]
1479
- action = "create"
1480
- status = 200
1481
- single = true
1482
- generate = { "id" = "uuid", "createdAt" = "now", "updatedAt" = "now" }
1469
+ action = "handler"
1470
+ handler = "webhook_create"
1483
1471
 
1484
1472
  [[operations]]
1485
1473
  name = "webhook_update"
@@ -74,13 +74,16 @@
74
74
  {
75
75
  "kind": "docs",
76
76
  "url": "https://linear.app/developers/webhooks",
77
- "version": "public page fetched 2026-09-15 (unversioned)",
78
- "sha256": "9b3c40e50c959d38ddbec2fd1b033cf29b92ad8be85161051cf4dd5df8033dc1",
79
- "bytes": 769613,
80
- "verified_at": "2026-09-15",
77
+ "version": "public page fetched 2026-10-10 (unversioned; first read 2026-09-15 at sha256 9b3c40e50c959d38ddbec2fd1b033cf29b92ad8be85161051cf4dd5df8033dc1)",
78
+ "sha256": "c4a4396cc544f32984868594be677a5938e054bce728b0d6650232738d0e1704",
79
+ "bytes": 753703,
80
+ "verified_at": "2026-10-10",
81
81
  "verification": "Fetched the HTML and computed SHA-256.",
82
82
  "used_for": [
83
- "the Webhook entity's documented purpose and resource types; webhook payloads mirror the GraphQL entities (no separate payload schema is modelled)"
83
+ "the Webhook entity's documented purpose and resource types; webhook payloads mirror the GraphQL entities (no separate payload schema is modelled)",
84
+ "the data change payload: action create/update/remove, type, actor (nullable), createdAt, data, url, updatedFrom on update, organizationId, webhookTimestamp in milliseconds",
85
+ "Linear-Delivery, Linear-Event and Linear-Signature (hex HMAC-SHA256 of the raw body under the webhook's secret)",
86
+ "webhookCreate takes teamId or allPublicTeams: true, url and resourceTypes"
84
87
  ]
85
88
  }
86
89
  ],
@@ -126,8 +129,9 @@
126
129
  "path": "connector.toml",
127
130
  "interface": "REST-shaped routes of this world (not vendor paths); the vendor exposes only POST https://api.linear.app/graphql",
128
131
  "operations": 150,
129
- "by_action": { "read": 55, "create": 24, "update": 28, "delete": 23, "handler": 20 },
130
- "handlers": ["issue_create", "comment_create", "archive", "unarchive", "organization"],
132
+ "by_action": { "read": 55, "create": 23, "update": 26, "delete": 21, "handler": 25 },
133
+ "handlers": ["issue_create", "comment_create", "archive", "unarchive", "organization", "updated", "removed", "webhook_create"],
134
+ "webhooks": "[webhooks] over linear_webhooks (url, resourceTypes, secret, enabled; scope teamId), signing linear; issue_create, comment_create and the updated/removed handlers on issues and comments deliver Linear's data change payload with the resource type (Issue, Comment) as the event type",
131
135
  "entities_without_routes": {
132
136
  "linear_roadmaps": "every roadmap root query and mutation carries @deprecated in the pinned SDL (use initiatives); the entity stays because RoadmapToProject mutations are not deprecated and reference it"
133
137
  }
@@ -137,6 +141,12 @@
137
141
  "WorkflowStateType, Issue.priority bounds and the description-derived uniqueness constraints come from field descriptions, not GraphQL types; User.email and Issue.identifier uniqueness come from the brief; the live API was not queried to confirm enforcement",
138
142
  "the 90 remaining Node types (agents, releases, notifications, custom views, favorites, integrations, OAuth, audit, drafts, history, search results, etc.) are not modelled",
139
143
  "live introspection of https://api.linear.app/graphql was not run (no credential); the SDL is the SDK's published copy at the pinned commit",
140
- "webhook payload shapes are not modelled as entities; only the Webhook resource is"
144
+ "webhook payload shapes are not modelled as entities; only the Webhook resource is",
145
+ "a delivered payload's data is the stored row; Linear's live payload may nest related objects (team, state, labels) the row carries as ids",
146
+ "actor is always null: the world has no viewer to name as the user behind an API key",
147
+ "webhookId is not in the payload: one event's body is signed alike for every subscription, so it cannot name each one; Linear-Timestamp is not sent by the linear signer",
148
+ "the generated secret's format (64 hex characters) and webhookCreate's defaults (enabled true per WebhookCreateInput; allPublicTeams false) for fields the input leaves out",
149
+ "issue and comment archive/unarchive send no webhook: the docs do not say which action Linear sends for them",
150
+ "allPublicTeams is not checked against Team.private: a webhook with no teamId receives every team's events"
141
151
  ]
142
152
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "linear_webhooks": [
3
3
  {
4
- "allPublicTeams": false,
4
+ "allPublicTeams": true,
5
5
  "archivedAt": null,
6
6
  "createdAt": "2026-03-02T09:00:00.000Z",
7
7
  "creatorId": "6d9fa919-d264-5efd-b52e-a58dd3a7acb7",
@@ -12,10 +12,26 @@
12
12
  "Issue",
13
13
  "Comment"
14
14
  ],
15
- "secret": null,
16
- "teamId": "cf85bd5a-a2bb-513e-ba81-6dea4c6c5074",
15
+ "secret": "example-issue-sync-signing-secret",
16
+ "teamId": null,
17
17
  "updatedAt": "2026-03-02T09:00:00.000Z",
18
18
  "url": "https://hooks.example.com/linear"
19
+ },
20
+ {
21
+ "allPublicTeams": false,
22
+ "archivedAt": null,
23
+ "createdAt": "2026-04-14T15:30:00.000Z",
24
+ "creatorId": "404e9b3b-5fd4-5f5c-8763-c8ff12f89e8b",
25
+ "enabled": false,
26
+ "id": "0b6f2c1e-4a7d-5e93-9c48-2d1f7a6b3e05",
27
+ "label": "Growth comment digest",
28
+ "resourceTypes": [
29
+ "Comment"
30
+ ],
31
+ "secret": "example-growth-digest-signing-secret",
32
+ "teamId": "2993d931-e0b1-5ff4-b3b9-1e7a012ea0bb",
33
+ "updatedAt": "2026-05-01T08:00:00.000Z",
34
+ "url": "https://digest.example.org/linear/comments"
19
35
  }
20
36
  ]
21
37
  }
@@ -0,0 +1,71 @@
1
+ """Linear's data change webhooks, end to end: register a webhook, write an issue, and read what the
2
+ session's feed says each receiver got.
3
+
4
+ Runs under ``gateway worlds test`` with ``WORLD_URL`` (the served world, the ``default`` scenario
5
+ seeded) and ``WORLD_API_KEY`` in the environment.
6
+ """
7
+
8
+ import hashlib
9
+ import hmac
10
+ import json
11
+ import os
12
+ import urllib.request
13
+
14
+ import pytest
15
+
16
+ URL = os.environ["WORLD_URL"]
17
+ KEY = os.environ["WORLD_API_KEY"]
18
+ PLATFORM = "cf85bd5a-a2bb-513e-ba81-6dea4c6c5074"
19
+ RECEIVER = "https://receiver.example.org/linear"
20
+ SECRET = "example-receiver-signing-secret"
21
+
22
+
23
+ def call(method, path, body=None):
24
+ request = urllib.request.Request(
25
+ URL + path,
26
+ method=method,
27
+ data=None if body is None else json.dumps(body).encode(),
28
+ headers={"Authorization": KEY, "Content-Type": "application/json"},
29
+ )
30
+ with urllib.request.urlopen(request) as reply:
31
+ raw = reply.read()
32
+ return json.loads(raw) if raw else None
33
+
34
+
35
+ def head():
36
+ return call("POST", "/__session/webhooks", {"tail": True, "subscriptions": False})["next"]
37
+
38
+
39
+ def received_after(seq):
40
+ page = call("POST", "/__session/webhooks", {"after": seq, "subscriptions": False})
41
+ return [d for d in page["deliveries"] if d["url"] == RECEIVER]
42
+
43
+
44
+ @pytest.fixture(scope="module", autouse=True)
45
+ def receiver():
46
+ return call("POST", "/webhooks", {"url": RECEIVER, "secret": SECRET, "resourceTypes": ["Issue"], "allPublicTeams": True})
47
+
48
+
49
+ def test_a_registered_webhook_receives_the_issue_signed_with_its_secret():
50
+ seq = head()
51
+ issue = call("POST", "/issues", {"teamId": PLATFORM, "title": "Receiver acknowledges late"})
52
+
53
+ (delivery,) = received_after(seq)
54
+ payload = delivery["payload"].encode()
55
+ assert delivery["headers"]["linear-signature"] == hmac.new(SECRET.encode(), payload, hashlib.sha256).hexdigest()
56
+ assert delivery["headers"]["linear-event"] == "Issue"
57
+ body = json.loads(payload)
58
+ assert (body["action"], body["type"], body["data"]["id"]) == ("create", "Issue", issue["id"])
59
+ assert body["url"] == issue["url"]
60
+
61
+
62
+ def test_an_issue_update_names_what_it_changed_and_a_comment_does_not_reach_an_issue_only_webhook():
63
+ issue = call("POST", "/issues", {"teamId": PLATFORM, "title": "Receiver drops retries"})
64
+ seq = head()
65
+ call("PATCH", f"/issues/{issue['id']}", {"priority": 1})
66
+ call("POST", "/comments", {"issueId": issue["id"], "body": "Reproduced."})
67
+
68
+ (delivery,) = received_after(seq)
69
+ body = json.loads(delivery["payload"])
70
+ assert body["action"] == "update"
71
+ assert body["updatedFrom"]["priority"] == issue["priority"]
@@ -37,6 +37,7 @@ class AccessKind(Enum):
37
37
 
38
38
 
39
39
  READ_KINDS = frozenset({AccessKind.SELECT, AccessKind.READ, AccessKind.FUNCTION, AccessKind.RECURSIVE})
40
+ JSON_TABLE_FUNCTIONS = frozenset({"json_each", "json_tree"})
40
41
 
41
42
 
42
43
  @dataclass(frozen=True)
@@ -74,7 +75,7 @@ class ReadOnlyDoor(Door):
74
75
  return not access.unsafe_function
75
76
 
76
77
  def _readable(self, table: str | None, entities: frozenset[str]) -> bool:
77
- if table in entities or table == RUNTIME_PARAMETERS:
78
+ if table in entities or table == RUNTIME_PARAMETERS or table in JSON_TABLE_FUNCTIONS:
78
79
  return True
79
80
  return self.private and table in RUNTIME_TABLES
80
81
 
@@ -5,6 +5,8 @@ A tool or a route whose handler raises is answered the same way on every door:
5
5
  * ``AttributeError`` / ``TypeError`` / ``NameError`` are the author's bug
6
6
  (``store.upsert`` on a store with no ``upsert``, a misspelled name, a
7
7
  wrong argument shape) — status **400**, ``error: "handler"``.
8
+ * ``Refusal(status, body)`` is the vendor saying no (not found, invalid,
9
+ forbidden) — its own 4xx status and body, as the caller should see them.
8
10
  * Anything else is a failure inside the handler's own logic — status **500**,
9
11
  ``error: "engine"``.
10
12
 
@@ -36,6 +38,18 @@ HANDLER_BUG_ERRORS: tuple[type[BaseException], ...] = (
36
38
  NameError,
37
39
  )
38
40
 
41
+
42
+ class Refusal(Exception):
43
+ """A handler's 4xx answer, raised: the body goes out as given, never checked against the tool's output."""
44
+
45
+ def __init__(self, status: int, body: Any = None):
46
+ if isinstance(status, bool) or not isinstance(status, int) or not 400 <= status <= 499:
47
+ raise TypeError(f"Refusal takes a status from 400 to 499, not {status!r}")
48
+ super().__init__(f"refused with {status}")
49
+ self.status = status
50
+ self.body = body
51
+
52
+
39
53
  _DETAIL_LIMIT = 2000
40
54
  _FIELD_LIMIT = 256
41
55
  _SURROGATE = re.compile("[\ud800-\udfff]")
@@ -84,12 +98,24 @@ def engine_failure_body(handler: str, error: BaseException) -> dict:
84
98
 
85
99
 
86
100
  def failure_answer(handler: str, error: Exception) -> tuple[int, dict]:
87
- """A handler's raise as its ``(status, body)``: its author's bug or the engine's failure."""
101
+ """A handler's raise as its ``(status, body)``: a refusal, its author's bug or the engine's failure."""
102
+ if isinstance(error, Refusal):
103
+ return refusal_answer(handler, error)
88
104
  if isinstance(error, HANDLER_BUG_ERRORS):
89
105
  return 400, handler_bug_body(handler, error)
90
106
  return 500, engine_failure_body(handler, error)
91
107
 
92
108
 
109
+ def refusal_answer(handler: str, refusal: Refusal) -> tuple[int, Any]:
110
+ """A refusal as it is answered, its body checked now (it may have changed since the raise)."""
111
+ if isinstance(refusal.body, bytes):
112
+ return 400, handler_bug_body(handler, TypeError("a Refusal body is JSON, not bytes"))
113
+ problem = unencodable(refusal.body)
114
+ if problem is not None:
115
+ return 400, handler_bug_body(handler, problem, "a Refusal body is not JSON: ")
116
+ return refusal.status, refusal.body
117
+
118
+
93
119
  def unencodable(body: Any) -> Exception | None:
94
120
  """Why a body cannot go out as JSON, or None when it can (bytes go out as they are)."""
95
121
  if isinstance(body, bytes):
@@ -26,7 +26,7 @@ JOURNAL_TABLES = frozenset(JOURNAL_KEYS)
26
26
  MAX_JOURNAL_REQUESTS = 20_000
27
27
  NOT_RECORDED = "not recorded: only a World Host session records the requests its world receives"
28
28
  LINKED_NOT_RECORDED = "not recorded for a linked world: the root world's verifiers and the task's checks read it"
29
- VIAS = ("api", "ui", "tool")
29
+ VIAS = ("api", "ui", "tool", "webhook")
30
30
  JSON_HINTS = ("json",)
31
31
  WITHHELD_ROUTE_BODY = ["body", "selectors"]
32
32
  WITHHELD_TOOL_ARGS = ["args", "selectors"]
@@ -244,7 +244,8 @@ LINKED_JOURNAL = WorldJournal.unrecorded(LINKED_NOT_RECORDED)
244
244
 
245
245
 
246
246
  class CallsView:
247
- """A request no route took and a tool call the door refused are the journal's alone: they never were calls."""
247
+ """A request no route took, a tool call the door refused and a webhook the world sent (``via``
248
+ webhook) are the journal's alone: they never were the agent's calls."""
248
249
 
249
250
  def __init__(self, spec: Spec | None, redaction: CallRedaction, admitted: Callable[[str], bool]) -> None:
250
251
  self.spec = spec
@@ -255,7 +256,7 @@ class CallsView:
255
256
  return [call for call in map(self._call, journal.entries) if call is not None]
256
257
 
257
258
  def _call(self, entry: JournalEntry) -> dict | None:
258
- if entry.operation is None:
259
+ if entry.operation is None or entry.raw["via"] == "webhook":
259
260
  return None
260
261
  if entry.raw["via"] == "tool" and entry.raw["method"] is None:
261
262
  return self._tool(entry) if self.admitted(entry.operation) else None
@@ -306,6 +306,7 @@ def make_session_handler(
306
306
  "POST seed": seed,
307
307
  "POST call": world.call,
308
308
  "POST close": close,
309
+ "POST webhooks": lambda poll: calls.webhook_page(world.world.webhooks, poll),
309
310
  }
310
311
 
311
312
  class Handler(WorldRequestHandler):
@@ -142,6 +142,7 @@ class Namespace:
142
142
  return candidate, True
143
143
 
144
144
 
145
+ GENERIC_SUFFIXES = frozenset({"item", "items", "entry", "summary", "response", "detail", "details", "object", "record", "resource"})
145
146
  SCALARS = frozenset({"string", "integer", "number", "boolean"})
146
147
 
147
148
 
@@ -175,8 +176,9 @@ class EntityKey:
175
176
 
176
177
  def detect(self, *, lookups: tuple[str, ...] = (), fallback: bool = True) -> str | None:
177
178
  """:meth:`declared`, else the field a route's own ``{segment}`` looks the row up by
178
- (``/works/{doi}`` → ``DOI``; nested, ``/studies/{nctId}`` → a JSON Pointer), else
179
- (when ``fallback``) the first required scalar."""
179
+ (``/works/{doi}`` → ``DOI``; nested, ``/studies/{nctId}`` → a JSON Pointer), else the resource's
180
+ own id named from a shorter form of the schema or its namespace (``messages_MessageItem`` →
181
+ ``message_id``), else (when ``fallback``) the first required scalar."""
180
182
  declared = self.declared()
181
183
  if declared is not None:
182
184
  return declared
@@ -184,6 +186,9 @@ class EntityKey:
184
186
  found = self.top_level(own) or self.nested(own)
185
187
  if found is not None:
186
188
  return found
189
+ resource = next((name for name in self._resource_id_like() if self._keyable(name)), None)
190
+ if resource is not None:
191
+ return resource
187
192
  if not fallback:
188
193
  return None
189
194
  return next((name for name in self.properties if name in self.required and self._keyable(name)), None)
@@ -252,9 +257,19 @@ class EntityKey:
252
257
  return types if isinstance(types, str) and not resolved.get("properties") else None
253
258
 
254
259
  def _id_like(self) -> list[str]:
255
- singular = Names.snake(self.source)
256
- camel = re.sub(r"_([a-z0-9])", lambda m: m.group(1).upper(), singular)
257
- candidates = ["id", "ID", "Id", f"{camel}Id", f"{camel}_id", f"{singular}_id", f"{singular}Id", f"{camel}ID"]
260
+ return self._named_ids(["id", "ID", "Id"], [Names.snake(self.source)])
261
+
262
+ def _resource_id_like(self) -> list[str]:
263
+ own = self.source.partition("_")[2] if self.source.partition("_")[2][:1].isupper() else self.source
264
+ words = [word for word in Names.snake(own).split("_") if word]
265
+ trailing = ["_".join(words[start:]) for start in range(len(words)) if words[start:] != [words[-1]] or words[-1] not in GENERIC_SUFFIXES]
266
+ meaningful = words[:-1] if len(words) > 1 and words[-1] in GENERIC_SUFFIXES else words
267
+ return self._named_ids([], [*trailing, "_".join(meaningful), *meaningful[-1:]])
268
+
269
+ def _named_ids(self, candidates: list[str], stems: list[str]) -> list[str]:
270
+ for stem in stems:
271
+ camel = re.sub(r"_([a-z0-9])", lambda m: m.group(1).upper(), stem)
272
+ candidates = [*candidates, f"{camel}Id", f"{camel}_id", f"{stem}_id", f"{stem}Id", f"{camel}ID"]
258
273
  return [c for c in dict.fromkeys(candidates) if c in self.properties]
259
274
 
260
275
  def _keyable(self, name: str) -> bool: