@withgateway/sdk 0.3.3 → 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 (158) hide show
  1. package/README.md +4 -3
  2. package/dist/cli.js +3005 -1401
  3. package/dist/cli.js.map +1 -1
  4. package/dist/cli.mjs +2996 -1392
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/files/index.js +128 -37
  7. package/dist/files/index.js.map +1 -1
  8. package/dist/files/index.mjs +126 -35
  9. package/dist/files/index.mjs.map +1 -1
  10. package/dist/hooks/index.d.mts +1 -1
  11. package/dist/hooks/index.d.ts +1 -1
  12. package/dist/hooks/index.js +124 -11
  13. package/dist/hooks/index.js.map +1 -1
  14. package/dist/hooks/index.mjs +124 -11
  15. package/dist/hooks/index.mjs.map +1 -1
  16. package/dist/{index-C3UzD0G3.d.mts → index-CDPQBsU5.d.mts} +19 -3
  17. package/dist/{index-C3UzD0G3.d.ts → index-CDPQBsU5.d.ts} +19 -3
  18. package/dist/{index-mJhG3vZU.d.mts → index-Di9nNqOY.d.mts} +26 -3
  19. package/dist/{index-DUHmS74p.d.ts → index-LA-PMRJT.d.ts} +26 -3
  20. package/dist/index.d.mts +4 -4
  21. package/dist/index.d.ts +4 -4
  22. package/dist/index.js +1078 -260
  23. package/dist/index.js.map +1 -1
  24. package/dist/index.mjs +1040 -251
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/replay/index.d.mts +1 -1
  27. package/dist/replay/index.d.ts +1 -1
  28. package/dist/replay/index.js.map +1 -1
  29. package/dist/replay/index.mjs.map +1 -1
  30. package/dist/traces/index.js +125 -34
  31. package/dist/traces/index.js.map +1 -1
  32. package/dist/traces/index.mjs +123 -32
  33. package/dist/traces/index.mjs.map +1 -1
  34. package/dist/tracing/index.d.mts +1 -1
  35. package/dist/tracing/index.d.ts +1 -1
  36. package/dist/tracing/index.js +7 -1
  37. package/dist/tracing/index.js.map +1 -1
  38. package/dist/tracing/index.mjs +7 -1
  39. package/dist/tracing/index.mjs.map +1 -1
  40. package/dist/worlds/index.d.mts +819 -438
  41. package/dist/worlds/index.d.ts +819 -438
  42. package/dist/worlds/index.js +912 -236
  43. package/dist/worlds/index.js.map +1 -1
  44. package/dist/worlds/index.mjs +908 -232
  45. package/dist/worlds/index.mjs.map +1 -1
  46. package/package.json +1 -1
  47. package/runtime/gatewaysdk/environment/_bundle.py +4 -6
  48. package/runtime/gatewaysdk/environment/_materialize.py +5 -25
  49. package/runtime/gatewaysdk/environment/_world.py +82 -66
  50. package/runtime/gatewaysdk/environment/backing.py +20 -24
  51. package/runtime/gatewaysdk/environment/core.py +1 -16
  52. package/runtime/gatewaysdk/environment/legacy_sqlite.py +14 -27
  53. package/runtime/gatewaysdk/environment/runtime.py +45 -2
  54. package/runtime/gatewaysdk/environment/schema/admission.py +174 -0
  55. package/runtime/gatewaysdk/environment/schema/api.py +198 -474
  56. package/runtime/gatewaysdk/environment/schema/assertions.py +458 -0
  57. package/runtime/gatewaysdk/environment/schema/batch.py +3 -3
  58. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +1 -0
  59. package/runtime/gatewaysdk/environment/schema/cache_layout.py +5 -0
  60. package/runtime/gatewaysdk/environment/schema/call_capture.py +321 -0
  61. package/runtime/gatewaysdk/environment/schema/call_log.py +276 -18
  62. package/runtime/gatewaysdk/environment/schema/call_redaction.py +207 -19
  63. package/runtime/gatewaysdk/environment/schema/cast.py +15 -35
  64. package/runtime/gatewaysdk/environment/schema/compiler.py +4 -1
  65. package/runtime/gatewaysdk/environment/schema/conform.py +38 -35
  66. package/runtime/gatewaysdk/environment/schema/connector.py +94 -152
  67. package/runtime/gatewaysdk/environment/schema/connectors/confluence/connector.toml +1 -12
  68. package/runtime/gatewaysdk/environment/schema/connectors/custom/handlers.py +2 -1
  69. package/runtime/gatewaysdk/environment/schema/connectors/github/api/handlers.py +217 -58
  70. package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +10 -19
  71. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_webhooks.json +10 -2
  72. package/runtime/gatewaysdk/environment/schema/connectors/github/tests/webhooks.json +47 -0
  73. package/runtime/gatewaysdk/environment/schema/connectors/github/world.json +21 -0
  74. package/runtime/gatewaysdk/environment/schema/connectors/jamf/api/handlers.py +185 -18
  75. package/runtime/gatewaysdk/environment/schema/connectors/jamf/connector.toml +29 -14
  76. package/runtime/gatewaysdk/environment/schema/connectors/jamf/provenance.json +43 -12
  77. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_webhooks.json +2 -2
  78. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scope.toml +4 -17
  79. package/runtime/gatewaysdk/environment/schema/connectors/jamf/tests/webhooks.json +107 -0
  80. package/runtime/gatewaysdk/environment/schema/connectors/jamf/vendor-openapi.json +1 -1
  81. package/runtime/gatewaysdk/environment/schema/connectors/linear/api/handlers.py +85 -1
  82. package/runtime/gatewaysdk/environment/schema/connectors/linear/connector.toml +19 -31
  83. package/runtime/gatewaysdk/environment/schema/connectors/linear/provenance.json +18 -8
  84. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/webhooks.json +19 -3
  85. package/runtime/gatewaysdk/environment/schema/connectors/linear/tests/test_webhooks.py +71 -0
  86. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/connector.toml +2 -5
  87. package/runtime/gatewaysdk/environment/schema/cors.py +54 -0
  88. package/runtime/gatewaysdk/environment/schema/credentials.py +313 -8
  89. package/runtime/gatewaysdk/environment/schema/data.py +14 -13
  90. package/runtime/gatewaysdk/environment/schema/database/base.py +106 -165
  91. package/runtime/gatewaysdk/environment/schema/database/guard.py +45 -37
  92. package/runtime/gatewaysdk/environment/schema/database/reads.py +169 -0
  93. package/runtime/gatewaysdk/environment/schema/database/sqlite.py +57 -31
  94. package/runtime/gatewaysdk/environment/schema/declared_routes.py +210 -0
  95. package/runtime/gatewaysdk/environment/schema/door.py +899 -0
  96. package/runtime/gatewaysdk/environment/schema/envelope.py +86 -28
  97. package/runtime/gatewaysdk/environment/schema/grading.py +58 -86
  98. package/runtime/gatewaysdk/environment/schema/handler_errors.py +52 -5
  99. package/runtime/gatewaysdk/environment/schema/host.py +229 -1695
  100. package/runtime/gatewaysdk/environment/schema/host_control.py +144 -0
  101. package/runtime/gatewaysdk/environment/schema/host_handoff.py +370 -0
  102. package/runtime/gatewaysdk/environment/schema/host_loops.py +97 -0
  103. package/runtime/gatewaysdk/environment/schema/host_owners.py +121 -0
  104. package/runtime/gatewaysdk/environment/schema/host_proxy.py +111 -0
  105. package/runtime/gatewaysdk/environment/schema/host_requests.py +6 -0
  106. package/runtime/gatewaysdk/environment/schema/host_session.py +126 -0
  107. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +79 -21
  108. package/runtime/gatewaysdk/environment/schema/host_transfers.py +127 -0
  109. package/runtime/gatewaysdk/environment/schema/host_versions.py +242 -0
  110. package/runtime/gatewaysdk/environment/schema/host_workers.py +577 -0
  111. package/runtime/gatewaysdk/environment/schema/journal.py +438 -0
  112. package/runtime/gatewaysdk/environment/schema/ledger_spill.py +828 -0
  113. package/runtime/gatewaysdk/environment/schema/local.py +32 -116
  114. package/runtime/gatewaysdk/environment/schema/openapi_schemas.py +20 -5
  115. package/runtime/gatewaysdk/environment/schema/platform.py +29 -234
  116. package/runtime/gatewaysdk/environment/schema/request_body.py +238 -0
  117. package/runtime/gatewaysdk/environment/schema/request_ledger.py +958 -0
  118. package/runtime/gatewaysdk/environment/schema/route_bindings.py +25 -3
  119. package/runtime/gatewaysdk/environment/schema/route_miss.py +54 -0
  120. package/runtime/gatewaysdk/environment/schema/runtime.py +136 -176
  121. package/runtime/gatewaysdk/environment/schema/scaffold.py +2 -1
  122. package/runtime/gatewaysdk/environment/schema/session_files.py +133 -24
  123. package/runtime/gatewaysdk/environment/schema/session_move.py +275 -0
  124. package/runtime/gatewaysdk/environment/schema/skills/agents/connector-template-author.md +5 -1
  125. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +8 -9
  126. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  127. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +50 -28
  128. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +12 -8
  129. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +20 -22
  130. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +25 -25
  131. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +24 -16
  132. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +71 -7
  133. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +182 -0
  134. package/runtime/gatewaysdk/environment/schema/snapshot.py +150 -30
  135. package/runtime/gatewaysdk/environment/schema/spill_files.py +228 -0
  136. package/runtime/gatewaysdk/environment/schema/tasks.py +229 -323
  137. package/runtime/gatewaysdk/environment/schema/tools_world.py +103 -203
  138. package/runtime/gatewaysdk/environment/schema/validation.py +69 -1
  139. package/runtime/gatewaysdk/environment/schema/verbs.py +38 -36
  140. package/runtime/gatewaysdk/environment/schema/webhooks.py +687 -0
  141. package/runtime/gatewaysdk/environment/schema/worker.py +6 -4
  142. package/runtime/gatewaysdk/environment/schema/workers.py +203 -39
  143. package/runtime/gatewaysdk/environment/schema/world_host.py +970 -0
  144. package/runtime/gatewaysdk/environment/schema/world_tests.py +83 -11
  145. package/runtime/gatewaysdk/environment/world.py +1 -1
  146. package/runtime/gatewaysdk/environment/world_session_contract.py +14 -0
  147. package/skills/agents/connector-template-author.md +5 -1
  148. package/skills/benchmarks-getting-started/SKILL.md +8 -9
  149. package/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  150. package/skills/connector-schema-authoring/SKILL.md +50 -28
  151. package/skills/connector-schema-authoring/connector-worlds.md +282 -18
  152. package/skills/connector-schema-authoring/world-schema.md +7 -6
  153. package/skills/world-data-ingestion/ROWS.md +12 -8
  154. package/skills/world-data-ingestion/SKILL.md +20 -22
  155. package/skills/worlds-getting-started/SKILL.md +25 -25
  156. package/skills/worlds-getting-started/references/cli-mcp-map.md +24 -16
  157. package/skills/worlds-getting-started/references/gotchas.md +71 -7
  158. package/skills/worlds-getting-started/references/journal-checks.md +182 -0
@@ -1,28 +1,4 @@
1
- """A schema world opened on this machine the way the World Host opens it.
2
-
3
- One :class:`LocalSession` is one session: the world's template copied into a
4
- scratch directory, its handlers loaded, every ``[dependencies]`` alias opened
5
- beside it from its ``path`` (dependency tools served as ``<alias>.<tool>``),
6
- and, when asked, an HTTP server on a loopback port. The server speaks the
7
- session verbs under ``/__session/`` for every schema world (``POST call``,
8
- ``GET state``, ``POST grade``, ``POST reset``, ``POST seed``, ``GET tools``,
9
- ``GET task``, ``POST close``, the host's own shapes) and, when the tree carries
10
- ``connector.toml``, the vendor routes beside them with the api pin as the key.
11
- Tool calls and HTTP requests hit the SAME store, as they do on the host. The
12
- runner's ``/__world/*`` routes answer only the session's own :attr:`LocalSession.admin`
13
- token, which ``worlds test`` hands its pytest files; the host serves none of them.
14
-
15
- The session is what an outside agent works against: ``GET task`` hands it the
16
- prompt it is to carry out and the verifiers that will grade it (a
17
- dependency's as ``<alias>/<name>``), the tools answer at ``POST call``, ``POST
18
- grade`` scores every world's state where it lives, and ``POST close`` ends the
19
- session — the server stops answering and whoever opened it (``gateway worlds
20
- serve``) returns.
21
-
22
- This is what ``gateway worlds call``, ``gateway worlds test`` and
23
- ``gateway worlds serve`` open; what passes here passes hosted, and a world
24
- that will not open here will not open there either.
25
- """
1
+ """A schema world opened on this machine the way the World Host opens it: what passes here passes hosted."""
26
2
 
27
3
  from __future__ import annotations
28
4
 
@@ -40,14 +16,15 @@ from typing import Any, Callable
40
16
 
41
17
  from . import snapshot as snapshots
42
18
  from .admin_routes import AdminToken
43
- from .api import Router, Via, WorldApp, load_api_settings, send_response, vendor_credential, with_query
19
+ from .api import Router, Via, WorldApp, load_api_settings, send_response, with_query
20
+ from .call_capture import WorldRequestHandler, write_body
44
21
  from .call_log import CallLog
45
22
  from .compiler import bundle_mode, fail
46
23
  from .conform import PIN
47
24
  from .connector import SPEC, load_spec
48
25
  from .dependencies import local_dependency_trees
49
26
  from .host_surfaces import UiSurface, api_target, cross_site, load_ui_surface, static_file
50
- from .runtime import client_grant, task_card
27
+ from .runtime import task_card
51
28
  from .tools_world import (
52
29
  DependencyWorld,
53
30
  ToolsTask,
@@ -63,9 +40,7 @@ LOCAL_TASK = ToolsTask(id="local", prompt="A local session; every verifier grade
63
40
 
64
41
 
65
42
  def has_http(root: str | Path) -> bool:
66
- """Whether the world serves HTTP at all: only a tree with ``connector.toml``
67
- has routes. A schema world without one is tools-only, and that is a whole
68
- world, not a broken one."""
43
+ """A schema world without ``connector.toml`` is tools-only: a whole world, not a broken one."""
69
44
  return (Path(root) / SPEC).is_file()
70
45
 
71
46
 
@@ -80,9 +55,6 @@ def load_local_version(root: Path, scratch: Path) -> ToolsVersion:
80
55
 
81
56
 
82
57
  def load_local_dependencies(root: Path, version: ToolsVersion, scratch: Path) -> dict[str, DependencyWorld]:
83
- """Every alias the manifest declares, opened from its ``path``. A pin with
84
- no path is refused by :func:`local_dependency_trees`: the platform resolves
85
- pins, this machine cannot."""
86
58
  out: dict[str, DependencyWorld] = {}
87
59
  for alias, tree in local_dependency_trees(root, version.dependencies).items():
88
60
  dep_version = load_local_version(tree, scratch / "deps" / alias)
@@ -99,7 +71,7 @@ class LocalSession:
99
71
  calls: CallLog
100
72
  app: WorldApp | None = None
101
73
  api_key: str | None = PIN
102
- #: The key to this session's ``/__world/*`` routes, minted when it opened.
74
+ #: The only key the runner's /__world/* routes answer, minted per session; the host serves none of them.
103
75
  admin: AdminToken = field(default_factory=AdminToken)
104
76
  ui: UiSurface | None = None
105
77
  #: The ui on its own origin, as the World Host lays it out, so a frontend built for the root runs unchanged.
@@ -110,27 +82,22 @@ class LocalSession:
110
82
 
111
83
  @property
112
84
  def base_url(self) -> str | None:
113
- """Where the server answers, or ``None`` when opened without one."""
114
85
  if self.server is None:
115
86
  return None
116
87
  return f"http://127.0.0.1:{self.server.server_port}"
117
88
 
118
89
  @property
119
90
  def routes(self) -> bool:
120
- """Whether the vendor routes are served beside the session verbs."""
121
91
  return has_http(self.root)
122
92
 
123
93
  @property
124
94
  def ui_url(self) -> str | None:
125
- """Where the world's ui answers: its own origin plus its entry, or None
126
- when the world declares none or the session has no server."""
127
95
  if self.ui_server is None or self.ui is None:
128
96
  return None
129
97
  return f"http://127.0.0.1:{self.ui_server.server_port}{self.ui.entry}"
130
98
 
131
99
  @property
132
100
  def ui_prefix_url(self) -> str | None:
133
- """The same page under ``/__ui/`` on the session's port, or None."""
134
101
  if self.server is None or self.ui is None:
135
102
  return None
136
103
  return f"{self.base_url}{UI_PREFIX}{self.ui.entry.lstrip('/')}"
@@ -140,14 +107,9 @@ class LocalSession:
140
107
  return list(self.world.served)
141
108
 
142
109
  def task(self) -> dict:
143
- """The task this session runs, as the outside agent reads it: the prompt
144
- to carry out, the tools it may call, and the verifiers that grade it,
145
- the root's by name and each dependency's as ``<alias>/<name>``."""
146
110
  return task_card(self.world)
147
111
 
148
112
  def call(self, tool: str, args: dict[str, Any]) -> dict:
149
- """The tool's ``{status, body}``; a refusal (a route's name, an unknown
150
- tool, one outside the task's list) is a 400 answer, not an error."""
151
113
  try:
152
114
  return self.world.call(tool, args)
153
115
  except ContractError as error:
@@ -175,8 +137,6 @@ class LocalSession:
175
137
  shutil.rmtree(self._scratch, ignore_errors=True)
176
138
 
177
139
  def wait(self, timeout: float | None = None) -> bool:
178
- """Block until the session is asked to end (``POST /__session/close``
179
- or :meth:`close`); ``False`` when ``timeout`` ran out first."""
180
140
  return self.closing.wait(timeout)
181
141
 
182
142
  def __enter__(self) -> LocalSession:
@@ -197,20 +157,8 @@ def open_world(
197
157
  ui_port: int | None = None,
198
158
  api_key: str | None = PIN,
199
159
  ) -> LocalSession:
200
- """Open one session of the world at ``root``.
201
-
202
- ``task`` selects a task the world declares (its prompt is served, its
203
- verifiers grade — the root's and, per its ``worlds``, each dependency's —
204
- and its seed is laid); ``None`` opens a plain session where every
205
- verifier grades.
206
- ``scenario`` starts the root in one of its ``scenarios/<name>``, the
207
- overlay replacing whole entities on the default state. ``http`` starts the
208
- server: the session verbs under ``/__session/`` for every world, the
209
- vendor routes beside them when the world has ``connector.toml``. A world
210
- that declares ``[ui]`` gets a second listener for the page on its own
211
- origin (``ui_port``; the next port up when ``port`` is fixed, any free
212
- one when it is 0), the layout the host serves it in.
213
- """
160
+ """``task`` None opens a plain session every verifier grades; ``ui_port`` None is the next port up from a fixed
161
+ ``port``, any free one when ``port`` is 0."""
214
162
  root = Path(root)
215
163
  scratch = tempfile.mkdtemp(prefix="gateway-local-")
216
164
  closing = threading.Event()
@@ -224,7 +172,7 @@ def open_world(
224
172
  f"no task '{task}' in {root.name}; it has {', '.join(sorted(version.tasks)) or 'none'}",
225
173
  )
226
174
  spec = load_spec(root) if has_http(root) else None
227
- calls = CallLog.for_spec(spec) if spec is not None else CallLog()
175
+ calls = CallLog.for_spec(spec, secret=api_key)
228
176
  world = ToolsWorld(
229
177
  version,
230
178
  Path(scratch) / "session",
@@ -245,15 +193,13 @@ def open_world(
245
193
  if http:
246
194
  if app is not None:
247
195
  ui = load_ui_surface(root)
248
- server = bind_server(
249
- host, port, make_session_handler(world, app, calls, closing, ui=ui, api_key=api_key)
250
- )
196
+ server = bind_server(host, port, make_session_handler(world, app, calls, closing, ui=ui))
251
197
  threading.Thread(target=server.serve_forever, daemon=True).start()
252
198
  if ui is not None:
253
199
  ui_server = bind_server(
254
200
  host,
255
201
  ui_port if ui_port is not None else (port + 1 if port else 0),
256
- make_session_handler(world, app, calls, closing, ui=ui, api_key=api_key, ui_origin=True),
202
+ make_session_handler(world, app, calls, closing, ui=ui, ui_origin=True),
257
203
  )
258
204
  threading.Thread(target=ui_server.serve_forever, daemon=True).start()
259
205
  except BaseException:
@@ -278,8 +224,7 @@ def open_world(
278
224
 
279
225
 
280
226
  def port_owner(port: int) -> str | None:
281
- """``pid <n> (<command>)`` of whatever listens on ``port``, from ``lsof`` when this
282
- machine has it; None when nothing can be said. Best effort, never an error."""
227
+ """Best effort from ``lsof``, never an error; None when nothing can be said."""
283
228
  try:
284
229
  found = subprocess.run(
285
230
  ["lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fpc"],
@@ -302,9 +247,8 @@ def port_owner(port: int) -> str | None:
302
247
 
303
248
 
304
249
  def bind_server(host: str, port: int, handler: type[BaseHTTPRequestHandler]) -> ThreadingHTTPServer:
305
- """The session's server on ``host:port``, or a refusal that NAMES the port and,
306
- when it can, who holds it: a bare ``Address already in use`` from a backgrounded
307
- serve goes unread while every curl after it reaches whatever else answers there."""
250
+ """A refusal names the port and its holder: a bare EADDRINUSE from a backgrounded serve goes unread while
251
+ every curl after it reaches whatever else answers there."""
308
252
  try:
309
253
  return ThreadingHTTPServer((host, port), handler)
310
254
  except OSError as error:
@@ -319,7 +263,6 @@ def bind_server(host: str, port: int, handler: type[BaseHTTPRequestHandler]) ->
319
263
 
320
264
 
321
265
  SESSION_PREFIX = "/__session/"
322
- #: The generated page's mount on the session port; a built ui gets its own origin, as on the host.
323
266
  UI_PREFIX = "/__ui/"
324
267
 
325
268
 
@@ -330,24 +273,11 @@ def make_session_handler(
330
273
  closing: threading.Event | None = None,
331
274
  *,
332
275
  ui: UiSurface | None = None,
333
- api_key: str | None = PIN,
334
276
  ui_origin: bool = False,
335
277
  ) -> type[BaseHTTPRequestHandler]:
336
- """The local server's handler: ``/__session/<verb>`` is the session (the
337
- host's control verbs, one session, no secret — this is loopback on the
338
- author's machine); ``/__ui/…`` the world's static ui when connector.toml
339
- declares one, and its ``api_path`` prefix the vendor routes with the pin
340
- presented for the page (the host does the same with the session cookie);
341
- any other path is the vendor route when the world has routes, else a 404
342
- that says where the tools are. ``POST close`` answers ``{closed: true}``
343
- and sets ``closing``: the opener tears the session down (a handler cannot
344
- stop the server it runs in). With ``ui_origin`` the handler is the ui's own
345
- origin instead: the page at ``/`` (every path that is not a file of it
346
- falls back to ``index.html``, for a client-side router) and its
347
- ``api_path`` prefix answered with the pin — nothing else, as on the host."""
278
+ """``/__session/`` takes no secret: it is loopback on the author's machine. ``POST close`` only sets ``closing``,
279
+ as a handler cannot stop the server it runs in; the opener tears the session down."""
348
280
  closing = closing if closing is not None else threading.Event()
349
- # Page calls go in as a granted client, as on the host, or an oauth2 world refuses them.
350
- grant = client_grant(app, api_key)
351
281
 
352
282
  def close() -> dict:
353
283
  closing.set()
@@ -358,8 +288,12 @@ def make_session_handler(
358
288
  fail("host", "a schema world has no [redact] policy; seed it with redact=off")
359
289
  return world.seed({"rows": rows, "mode": mode})
360
290
 
361
- def grade(report: str | None = None, context: dict | None = None) -> dict:
362
- # Only the host runs a session task's graders, which read the report and the other worlds' evidence.
291
+ def grade(
292
+ report: str | None = None, context: dict | None = None, journal: dict | None = None, grader: dict | None = None
293
+ ) -> dict:
294
+ # Only the host runs the session-task graders these feed; a local session records no journal.
295
+ if grader is not None:
296
+ fail("host", "a candidate grader is graded on a World Host session (worlds task try)")
363
297
  return world.grade()
364
298
 
365
299
  operations: dict[str, Callable[..., dict]] = {
@@ -372,15 +306,13 @@ def make_session_handler(
372
306
  "POST seed": seed,
373
307
  "POST call": world.call,
374
308
  "POST close": close,
309
+ "POST webhooks": lambda poll: calls.webhook_page(world.world.webhooks, poll),
375
310
  }
376
311
 
377
- class Handler(BaseHTTPRequestHandler):
312
+ class Handler(WorldRequestHandler):
378
313
  server_version = "gateway-world-local"
379
314
 
380
- def log_message(self, *_):
381
- pass
382
-
383
- def _serve(self, method: str) -> None:
315
+ def _dispatch(self, method: str) -> None:
384
316
  length = int(self.headers.get("Content-Length") or 0)
385
317
  raw = self.rfile.read(length) if length else b""
386
318
  path = self.path.split("?", 1)[0]
@@ -389,6 +321,9 @@ def make_session_handler(
389
321
  if app is not None and api_target(ui, path) is not None:
390
322
  return self._ui_api(method, path, raw, Via.UI)
391
323
  return self._ui(method, path)
324
+ origin = self.headers.get("Origin")
325
+ if origin and not _local_origin(origin):
326
+ return self._reply(403, {"error": "this session answers this machine's pages, not another site's"})
392
327
  if path.startswith(SESSION_PREFIX):
393
328
  return self._session(method, path[len(SESSION_PREFIX) :].strip("/"), raw)
394
329
  if ui is not None and (path == UI_PREFIX.rstrip("/") or path.startswith(UI_PREFIX)):
@@ -419,13 +354,10 @@ def make_session_handler(
419
354
  self.send_header(name, value)
420
355
  self.send_header("Content-Length", str(len(payload)))
421
356
  self.end_headers()
422
- self.wfile.write(payload)
357
+ write_body(self, payload)
423
358
 
424
359
  def _ui_api(self, method: str, path: str, raw: bytes, via: Via) -> None:
425
- """The page's same-origin api call: strip the ``api_path`` prefix
426
- and answer the route with the world's own credential for the pin,
427
- the way the host answers it for the session cookie. Only the ui
428
- port's prefix is ``via: ui``; the session port is the api origin."""
360
+ """Answers with the world's own credential for the pin, as the host does for the session cookie."""
429
361
  assert app is not None and ui is not None
430
362
  route = api_target(ui, path)
431
363
  assert route is not None
@@ -436,7 +368,7 @@ def make_session_handler(
436
368
  )
437
369
  query = self.path.split("?", 1)[1] if "?" in self.path else ""
438
370
  headers = {k.lower(): v for k, v in self.headers.items() if k.lower() not in ("cookie", "authorization")}
439
- credential_headers, credential_query = vendor_credential(app.router.spec, api_key or "", grant=grant)
371
+ credential_headers, credential_query = app.door.present()
440
372
  target = with_query(route + (f"?{query}" if query else ""), credential_query)
441
373
  status, body, extra = app.handle(
442
374
  method,
@@ -469,28 +401,12 @@ def make_session_handler(
469
401
  self.send_header("Content-Type", "application/json")
470
402
  self.send_header("Content-Length", str(len(data)))
471
403
  self.end_headers()
472
- self.wfile.write(data)
473
-
474
- def do_GET(self):
475
- self._serve("GET")
476
-
477
- def do_POST(self):
478
- self._serve("POST")
479
-
480
- def do_PUT(self):
481
- self._serve("PUT")
482
-
483
- def do_PATCH(self):
484
- self._serve("PATCH")
485
-
486
- def do_DELETE(self):
487
- self._serve("DELETE")
404
+ write_body(self, data)
488
405
 
489
406
  return Handler
490
407
 
491
408
 
492
409
  def _local_origin(origin: str) -> bool:
493
- """Whether a browser ``Origin`` names this machine's loopback."""
494
410
  host = urllib.parse.urlsplit(origin).hostname
495
411
  return host in ("127.0.0.1", "localhost", "::1")
496
412
 
@@ -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: