Dang Dagger Modules dang-dagger-modules
Authoring Dagger modules in Dang — dagger-module.toml setup, the main type & constructor, what becomes module API, self-calls (supported; annotate returns as Dagger.<Type>!), dependencies, enums/interfaces/scalars, directives (@check, @cache, @defaultPath, @agent), Workspace args, and caching pitfalls.
Use it when writing or reviewing a Dagger module implemented in Dang.
- Our test
- —
- not tested yet
- GitHub stars
- 17k
- dagger/dagger
- Added by
- 0
- members
- Updated
- Dec 6
- commit a919b7b
- Content
- 1 file
- no scripts · 12 KB
- License
- Apache 2.0
- free to use
What our test found
Not tested yet. Our model tries every skill on a realistic request and scores the result, the most popular skills first. Until then, the safety checks on the right still apply.
name: dang-dagger-modules description: Authoring Dagger modules in Dang — dagger-module.toml setup, the main type & constructor, what becomes module API, self-calls (supported; annotate returns as Dagger.<Type>!), dependencies, enums/interfaces/scalars, directives (@check, @cache, @defaultPath, @agent), Workspace args, and caching pitfalls. Use when writing or reviewing a Dagger module implemented in Dang.
Dagger Modules in Dang
Audience: people writing Dagger modules in Dang. For the language itself (syntax, nullability, copy-on-write mutation, control flow, GraphQL interop) see the dang-language skill; this skill covers only what is specific to Dang as a Dagger module SDK.
Mental model
- A Dang module is a directory of
.dangfiles plus a config namingdangas the SDK. All top-level.dangfiles in the source directory form one module (subdirectories and other files are ignored); declarations are order-independent across files. - No codegen, no container — the engine interprets Dang natively. There is no generated client: the Dagger API is auto-imported under the
Daggernamespace, and bare names work too (container.from(...)≡Dagger.container.from(...)). - Every public top-level declaration becomes module API:
type→ object (plus constructor),enum→ enum,interface→ interface.letkeeps a binding private. Customscalars are exposed as strings. - The main object is the type whose name matches the module name. Secondary types get module-prefixed schema names:
type Widgetin moduletestlives in the schema asTestWidget. - Self-calls are fully supported (always enabled for the Dang SDK — no experimental flag needed): a module can call its own functions through the engine via its own root binding (
test.foo,tuiQa). See the dedicated section — the return-type annotation rule is the #1 gotcha.
Module setup
# dagger-module.toml
name = "counter"
engineVersion = "v1.0.0"
[runtime]
source = "dang"- Create one with
dagger module init dang --name counterafterdagger module install dagger.io/sdk/dang; the SDK writesengineVersionduring generation. - A
dang.tomlbeside the module (between the source and module directories) declares its versions, and wins over the module config:[imports.Dagger] dagger = "vX.Y.Z"is the engine version (API, naming),dang = "X.Y"the Dang language version. - Without
dang = ...,engineVersionpicks the Dang language:< v0.21.5is Dang 1.0 (where.{ }is GraphQL selection);v0.21.5up tov1.0.0-beta.28is Dang 2.1 (.{ }is dot-block application,.{{ }}is selection, and"${x}"is literal text: interpolate with backticks, `hi ${x});>= v1.0.0-beta.28is Dang 2.5, where a type pattern spells the non-null type its arm binds (c: Cat! =>,e: Error! =>inrescue),"..."/"""..."""strings interpolate${...}and process escapes, and only a language tag may follow an opening""". Write'...'/'''...'''for verbatim text (shell with${VAR}or\continuations, regexes), or escape\${. Don't bump an old module'sengineVersionwithout checking its syntax (dang migrate -w --from 2.1rewrites a module that declares nodang), or pindang = "X.Y"`. - Dependencies are
[[dependencies]]tables (name = "gochild",source = "./gochild"), managed withdagger module client add/rm/updatefrom the module directory. Deps may use any SDK (Go, Python, TypeScript, Dang) side by side. disableDefaultFunctionCaching = true(top level) turns off default function caching module-wide (coarse alternative to per-function@cache).- Legacy
dagger.jsonmodules ("sdk": {"source": "dang"}or"sdk": "dang") still load. Their"sdk": {"experimental": {"SELF_CALLS": true}}is obsolete: self-calls graduated to a runtime-capability check and are always on for Dang.
Main type, constructor & API surface
type Greeter {
let secret: String! = "hidden" # private state, never exposed
name: String! # public data field (also a ctor param)
new(name: String! = "world") { # explicit constructor
self.name = name.capitalize
self # must end with self
}
greet: String! { "Hey, " + name } # computed field / zero-arg function
}- Without
new, the uninitialized public fields form an implicit constructor in declaration order (positional construction works). - Constructor args become top-level flags:
dagger api call counter --name alice greet. Arg names need not match field names; the body really executes. - Public is the default: bare typed declarations are exposed;
letis private — includingletfunctions, the idiom for internal helpers. Thepubkeyword is legacy: it still parses (as a no-op) and the formatter strips it — don't write it in new code. - A field with a body is a function/computed field; a plain typed field is data. Docstrings (
"""..."""before a declaration or arg) become API descriptions. - Private (
let) fields persist across calls: they serialize into the object's state and rehydrate on the next call. Chain state mutations copy-on-write style:with(x): Self! { self.x = x; self }. - Non-null args (
T!) are required; nullable args are optional — the idiom for optional inputs isarg: File = null. Map[...]cannot be exposed through the API; keep maps inletfields (they serialize fine privately). Ad-hoc record types can't be exposed either — declare a namedtype.Voidreturn marks an effect-only function; end the body withnull(or aVoid-typed call), and use.syncto force container execution.
Self-calls
A self-call invokes the module's own API through the engine, via the module's root binding (the module name in camelCase):
type Test {
containerEcho(msg: String!): Container! {
container.from("alpine").withExec(["echo", msg])
}
print(msg: String!): String! {
test.containerEcho(msg: msg).stdout # self-call
}
fresh: Dagger.Test! { test } # self-call the constructor
}- Return-type annotation rule: a function that returns a self-call result must declare the return as
Dagger.<SchemaTypeName>!— e.g.Dagger.Test!, orDagger.TestWidget!for a secondaryWidget— not the bare local type. A self-call yields the type as installed in the runtime schema (namespaced, carrying a GraphQL id); the bare local type is a different type. Annotating with the bare type makes the runtime receive a raw ID string where an object is expected. - Constructing locally (
Widget(x)) yields the bare localWidget!; only an actual API call yieldsDagger.TestWidget!. - Self-call results are real objects: fields read back fine (
test.fresh.getMessage), including on secondary types. - Self-calls also work when the module is used as a dependency, transitively.
- Bare
test(zero-arg constructor auto-call) is the way to reset to a fresh instance from inside a method.
Dependencies
- A dependency named
foois callable as the root bindingfoo:foo.curve(...),dangchild.value. Deps with constructor args are called like functions:engineDev(ws: source).test. - A dependency's types appear module-namespaced: dep
foo'senum EcCurveisFooEcCurve, depdep'sinterface GreeterisDepGreeter.
Enums, interfaces, scalars
enum Status { PENDING RUNNING DONE }— compare with==; CLI passes members verbatim (--status DONE).interface Local { greet(name: String!): String! }plustype Hey implements Local— implementers must not declare the synthesizedid: ID!field Dagger adds to every interface.- Structural conformance crosses module boundaries: an object matching a dep interface's shape passes as that interface without
implements. - Interface methods touching core types annotate them qualified:
apply(container: Dagger.Container!): Dagger.Container!. scalar Timestampis exposed as a String at the boundary; values arrive as strings.- Bare
JSONis Dang's builtin JSON-text scalar (text :: JSON!), beside its codec (JSON.encode,JSON.decode); data of any shape decodes intoDecoded. Dagger's schema scalar isDagger.JSON, as a Dagger API argument of typeJSONwants; convert between them with a cast (value :: Dagger.JSON!). - A Dagger object displays as the lazy query it is, in string interpolation,
toStringandprint:<Container: container.from(address: …)>, argument values elided. Nothing is sent to show it. Select.idwhere an ID is wanted.
Directives Dagger consumes
- Function-level:
@check(marks a check; typically onVoidreturns),@generate(on Changeset-returning generators),@up(onService!),@agent(see below),@cache. - Arg-level:
@defaultPath(path: ...)onDirectory!args — relative paths resolve against the module,"/"against the context root;@ignorePatterns(patterns: [...])filters with gitignore-style patterns (allowlisting via"!keep"works). Positional and named args both parse. - Placement: suffix (
screen: String! @cache(...)) or prefix on the line before the declaration. - Agent idiom:
agent(base: LLM!): LLM! @agent {
base.withTools(currentNode).withSystemPrompt(systemPrompt)
}Workspace args
- A
Workspace!-typed arg (bare orDagger.Workspace!) is auto-filled by the caller's workspace — no flag needed ondagger api call; for agents it's filled from the bound workspace and hidden from the model. let ws: Workspace!as an uninitialized field is the standard pattern for holding it. Read withws.file(...),ws.directory(path, exclude: [...]).- The mounted workspace is a plain snapshot with no `.git` —
git diffwon't work; useWorkspace.git.uncommitted(a Changeset) with.diffStats/.asPatch.
Caching pitfalls
- The engine memoizes function results by (object id, field, args) within a session. Side-effecting or live-reading functions must opt out:
@cache(policy: FunctionCachePolicy.Never)(mixes a per-call nonce into the call id).@cache(ttl: "5m")sets a time-to-live instead (a duration string, valid only with theDefaultpolicy). - Even with
Never, identical container execs still hit the exec cache — bust with a nonce:.withEnvVariable("NONCE", Random.string).
Shadowing core types
- A module may declare types shadowing core names (
type Container); the bare name then means the local type, andDagger.Container!/Dagger.containerdisambiguates back to core.
Pitfalls checklist
- Self-call return annotated with the bare local type instead of
Dagger.<T>!→ runtime gets a raw ID string. (Self-calls DO work — don't conclude otherwise from old comments.) - Missing
@cache(policy: FunctionCachePolicy.Never)on a stateful/live tool → the second call reuses the first result. - Exposing a
Map[...]or an ad-hoc record type → hard error. - Declaring
idwhen implementing a dep interface → error; omit it. - Using v1
.{ }selection in a>= v0.21.5module — that's dot-block now; select with.{{ }}. - A bare type pattern (
c: Cat =>) in a Dang 2.5 module → error; writec: Cat! =>. - A shell-ish
"${PATH}"in a Dang 2.5 module interpolates (or fails to resolvePATH), and a\in a"""string is an escape; write verbatim text as'${PATH}'or'''...'''. - Conversely,
"hi ${name}"in a Dang 2.1 module (engineVersionbefore v1.0.0-beta.28) is literal text, not an interpolation; use backticks. - Passing bare
JSONwhere a Dagger API wants itsJSONscalar → type mismatch; cast it,value :: Dagger.JSON!. - Only top-level type declarations become module types; types defined inside bodies aren't hoisted into the schema.